﻿'''' Last Modified on Dec 15, 2014 09.35 am.
Imports System.Data
Imports ADOEntityKYC
Imports System.Data.OleDb

Partial Class KYC_NonIndividualCDD
    Inherits Web.UI.BasePage

#Region " Variable Gobal "

    Dim ds As DataSet
    Dim clsRiskLevel As clsRiskLevel = New clsRiskLevel
    Dim clsDatabase As clsDatabase = New clsDatabase
    Dim KYCEntity As KYCEntities = New KYCEntities
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim clsLINQToDataTable As clsLINQToDataTable
    Dim TypeKYC As Integer = 0
    Dim CustSeq As Integer = 0
    Dim clsCheckLanguage As clsCheckLanguage
    Dim clsCheckID As clsCheckID
    Dim strMsg As String = ""
    Dim sql As String = ""
    Dim clsDataTable As clsLINQToDataTable
    Dim convertDate As clsDateFormat

    '''''' Prachak ''''''''''''''''''''''''''''''
    Dim dtAddedService As New DataTable
    Dim dtProduct As New DataTable
    Dim dtC_Cust_Category As New DataTable
    Dim dtIncome As New DataTable
    Dim dtSanc As New DataTable
    Dim dtPolitical As New DataTable
    Dim dtReason As New DataTable
    Dim dtBo As New DataTable
    Dim lvsSQL As String

    Dim clsValid As clsValidateData
    Dim intBeforeSelectIndex_Corp_Cate As Integer
    Dim intBeforeSelectIndex_Income As Integer
    Dim intBeforeSelectIndex_Politician As Integer
    Dim intBeforeSelectIndex_Reason As Integer
    Dim intBeforeSelectIndex_BO As Integer
    Dim intBeforeSelectIndex_Product As Integer
    Dim intBeforeSelectIndex_AddedService As Integer

    Private Enum enmStatusNewAcc
        NoHaveNewAcc = 0
        HaveNewAcc = 1
    End Enum

#End Region
    'ผู้ร่วมผลประโยชน์ 1679 ,1798
#Region "Even Page"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        clsValid = New clsValidateData()
        Try

            If (Session("PopAddedService") Is Nothing) Then
                Me.grdPRODUCT.DataSource = dtProduct
                grdPRODUCT.DataBind()
            End If

            If (Session("PopProduct") Is Nothing) Then
                Me.grdPRODUCT.DataSource = dtProduct
                grdPRODUCT.DataBind()
            End If

            If (Session("PopINCOME") Is Nothing) Then
                Me.grdPRODUCT.DataSource = dtProduct
                grdPRODUCT.DataBind()
            End If

            If (Session("PopCorpCate") Is Nothing) Then
                grdCorp_Cate.DataSource = dtC_Cust_Category
                grdCorp_Cate.DataBind()
            End If


            If (Session("PopPolitical") Is Nothing) Then
                grdPolitical.DataSource = dtPolitical
                grdPolitical.DataBind()
            End If

            If (Session("PopReason") Is Nothing) Then
                grdReason.DataSource = dtReason
                grdReason.DataBind()
            End If

            If (Session("PopBo") Is Nothing) Then
                grdBo.DataSource = dtBo
                grdBo.DataBind()
            End If

            Me.SetControl_Enable()

            btnAddIndividual.Attributes.Add("onclick", "window.showModalDialog('NonIndividualBoard.aspx?index=-1&CustSeq=0&TypeKYC=1&UNIQUEID=0', null, 'status:no; dialogWidth:1000px; dialogHeight:600px; help:no; scroll:yes; menubar:no; resizable:no')")
            btnAddNonIndividual.Attributes.Add("onclick", "window.showModalDialog('NonIndividualBoardNon.aspx?index=-1&CustSeq=0&TypeKYC=1&UNIQUEID=0', null, 'status:no; dialogWidth:1000px; dialogHeight:600px; help:no; scroll:yes; menubar:no; resizable:no')")

            ''''Prachak '''''''''''''''''''''''
            Me.btnFilter_BO.Attributes.Add("onclick", "NoDoubleSubmit(); setAmlistParam_BO(); popAMListWindow();")
            Me.btnFilter_CUST.Attributes.Add("onclick", "NoDoubleSubmit(); setAmlistParam(); popAMListWindow();")


            'Me.btnAddConcern_Person.Attributes.Add("onclick",
            '"window.showModalDialog('NonIndividualCorp.aspx?index=-1&CustSeq=0&TypeKYC=1&UNIQUEID=0', null, 'status:no; dialogWidth:1000px; dialogHeight:600px; help:no; scroll:yes; menubar:no; resizable:no')")

            ds = Session("ds")

            clsSessionMenuRight = Session("clsMenuRight")

            If Not TypeKYC = 4 Then
                btnCancel.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resMsgKYC.msgCancle) + "')")
                btnKYCNext.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resMsgKYC.msgKYCNext) + "')")
            End If

            If Not IsPostBack Then
                Session("TypeKYC") = Request.QueryString("TypeKYC")
                Session("CustSeq") = Request.QueryString("CUSTSEQ")
                TypeKYC = Session("TypeKYC")
                CustSeq = Session("CustSeq")

                chkIsLogin()
                CreateControlMP()
                loadDataToDropDown()
                txtSalaryPerMonth.Text = "0"
                txtSalaryPerMonth.Enabled = True
                rdoAnsSalary.SelectedValue = "1"
                rdoAcc.SelectedValue = "0"
                If TypeKYC = 1 Then
                    If Not Request.QueryString("Back") = "1" Then
                        AutoInput()
                    End If

                    '''''Prachak '''''''''''''''''''
                    Me.Bind_Data_togrid_Corp_Category()
                    Me.Bind_Data_togrid_Income_Source()
                    Me.Bind_Data_togrid_Sanction()
                    Me.Bind_Data_togrid_grdPolitical()
                    Me.Bind_Data_togrid_Reason()
                    Me.Bind_Data_togrid_BO()
                    Me.Bind_Data_togrid_Product()
                    Me.Bind_Data_togrdAddedService()
                    '''''''''''''''''''''''''''''''''

                    lblRiskNow.Visible = False
                    btnKYC.Visible = False
                    btnHistory.Visible = False



                ElseIf TypeKYC = 2 Then
                    btnHistory.Visible = True
                    BindingData()
                    BindingAcc(CustSeq)
                    indexBizChanging1()
                    indexBizChanging2()
                    indexBizChanging3()
                    If hdfApprCode_MCus.Value = "1" Then
                        btnCompile.Visible = False
                        btnEditCompile.Visible = False
                        lblTextMsg.Visible = False
                        btnAddIndividual.Visible = False
                        btnAddNonIndividual.Visible = False
                        btnEdit.Visible = False
                        btnDelete.Visible = False

                    End If

                    '''''Prachak '''''''''''''''''''
                    Me.Bind_Data_togrid_Corp_Category()
                    Me.Bind_Data_togrid_Income_Source()
                    Me.Bind_Data_togrid_Sanction()
                    Me.Bind_Data_togrid_grdPolitical()
                    Me.Bind_Data_togrid_Reason()
                    Me.Bind_Data_togrid_BO()
                    Me.Bind_Data_togrid_Product()
                    Me.Bind_Data_togrdAddedService()
                    '''''''''''''''''''''''''''''''''

                End If
                ''''''''''Bind grid ref'''''''''''''''''''''''
                Me.createStructure()
                grdRef.DataSource = ds.Tables("dsCustomerCom")
                grdRef.DataBind()
                Me.lblCount_Peaple_Cont.Text = ds.Tables("dsCustomerCom").Rows.Count
                ''''''''''''''''''''''''''''''''''''''''''''''
                setGrid()

                'If Not hdfApprCode_MCus.Value = "" Then
                '    If Not hdfApprCode_MCus.Value = 0 Then
                '        ScriptManager.RegisterStartupScript(UpdatePanel1, _
                '                                              UpdatePanel1.GetType(), _
                '                                              "clientScript", _
                '                                              "alert('" + "เนื่องจากติดการอนุมัติ กรุณาทำการอนุมัติก่อน" + "')", _
                '                                              True)
                '    End If
                'End If


            Else
                TypeKYC = Session("TypeKYC")
                CustSeq = Session("CustSeq")
            End If

            If Session("KYC") = "2" Or Session("KYC") = "5" Then
                rdoAcc.SelectedValue = "1"
                rdoAcc.Enabled = False
            End If
            If Session("KYC") = "5" And TypeKYC = 1 Then
                ddlTranType.SelectedValue = "2"

            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("ds") = ds
    End Sub


#End Region

#Region "SetForm"

    Sub CreateControlMP()
        Dim img As Image = CType(Master.FindControl("imgHead"), Image)
        img.ImageUrl = "~/img/LogoNonIndi.jpg"

        Dim page As Label = CType(Master.FindControl("lblPage"), Label)
        page.Text = "ประเมินความเสี่ยง"
    End Sub

#End Region

#Region "Event Dropdrown"

    Protected Sub ddlBusiness1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlBusiness1.SelectedIndexChanged
        indexBizChanging1()
        txtDes1.Text = ""
    End Sub


    Protected Sub ddlBusiness2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlBusiness2.SelectedIndexChanged
        indexBizChanging2()
        txtDes2.Text = ""
    End Sub

    Protected Sub ddlBusiness3_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlBusiness3.SelectedIndexChanged
        indexBizChanging3()
        txtDes3.Text = ""
    End Sub

    Protected Sub ddlBizType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlBizType.SelectedIndexChanged
        UpdatePanel9.Update()
        autoBizType()
    End Sub
#End Region

#Region "Event Button"

    Protected Sub btnCompile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCompile.Click
        Try
            If Session("chkKYC") = True Then
                statusValidation()
                Image1.ImageUrl = "~/img/icon/accept.png"
                Image2.ImageUrl = "~/img/icon/accept.png"
                Image3.ImageUrl = "~/img/icon/accept.png"
                Image4.ImageUrl = "~/img/icon/accept.png"
                Image5.ImageUrl = "~/img/icon/accept.png"
                Image6.ImageUrl = "~/img/icon/accept.png"
                Image7.ImageUrl = "~/img/icon/accept.png"
                Image8.ImageUrl = "~/img/icon/accept.png"
                Image9.ImageUrl = "~/img/icon/accept.png"
                Image14.ImageUrl = "~/img/icon/accept.png"
                GoTo compile
            End If
            ''''''''''''''''''''''''''''
            Me.FindHeighest_Score_All()

            If checkBeforeCompile() = True Then
compile:
                compileCDD()
                If (Panel1.Enabled = True) Then
                    Session("chkKYC") = Nothing
                    'RiskSummary()
                    If grdRef.Rows.Count = 0 Or lblLevelCom.Text = "0" Then
                        'btnNext.Visible = False
                        'btnSave.Visible = False
                        btnReport.Visible = False
                    ElseIf Session("KYC") = 3 Then
                        'btnNext.Visible = True
                        'btnSave.Visible = True
                        btnReport.Visible = True
                        RiskSummary()
                    Else
                        'btnNext.Visible = True
                        'btnSave.Visible = True
                        btnReport.Visible = True
                        RiskSummary()
                    End If

                    'If Session("KYC") = 3 Then
                    '    btnNext.Visible = True
                    '    btnSave.Visible = True
                    '    btnReport.Visible = True
                    '    RiskSummary()
                    'End If

                    Panel1.Enabled = False
                    btnCompile.Visible = False
                    btnEditCompile.Visible = True
                    btnReport.Visible = True
                Else
                    Panel1.Enabled = True
                    btnCompile.Visible = True
                    btnEditCompile.Visible = False
                    btnReport.Visible = False
                End If


            Else

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & strMsg & "')", True)

                'btnNext.Visible = False
                'btnSave.Visible = False
                btnReport.Visible = False

                txtRiskLevel.Text = ""
                lblLevelCom.Text = 0
                txtReason.Text = ""
                txtRiskLevel.BackColor = Drawing.Color.White


                txtBizRiskLevel.Text = ""
                lblOverview.Text = 0
                txtReasonOverview.Text = ""
                txtBizRiskLevel.BackColor = Drawing.Color.White

            End If


        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

    Protected Sub btnHistory_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHistory.Click
        Try
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "window.open('CDDHistory.aspx?CUSTSEQ=" & CInt(CustSeq) & "&CUSTTYPE=2" & "','_blank','scrollbars=1,Width:800px, Height:600px')", True)
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

#Region "Authority"

    Protected Sub btnAddIndividual_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddIndividual.Click
        Try
            grdRef.DataSource = ds.Tables("dsCustomerCom")
            grdRef.DataBind()
            setGrid()

            grdRef.SelectedIndex = -1

            If grdRef.Rows.Count = 0 Or lblLevelCom.Text = "0" Then
                'btnNext.Visible = False
                'btnSave.Visible = False
                btnReport.Visible = False
            Else
                'btnNext.Visible = True
                'btnSave.Visible = True
                btnReport.Visible = True
                RiskSummary()
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try

    End Sub

    Protected Sub btnAddNonIndividual_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddNonIndividual.Click
        Try
            grdRef.DataSource = ds.Tables("dsCustomerCom")
            grdRef.DataBind()
            setGrid()

            grdRef.SelectedIndex = -1

            If grdRef.Rows.Count = 0 Or lblLevelCom.Text = "0" Then
                'btnNext.Visible = False
                'btnSave.Visible = False
                btnReport.Visible = False
            Else
                'btnNext.Visible = True
                'btnSave.Visible = True
                btnReport.Visible = True
                RiskSummary()
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

    Protected Sub btnEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        Try
            If grdRef.SelectedIndex = -1 Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & Resources.resMsgKYC.msgSelect & "')", True)
            Else
                grdRef.DataSource = ds.Tables("dsCustomerCom")
                grdRef.DataBind()
                setGrid()

                grdRef.SelectedIndex = -1
                btnEdit.Attributes.Clear()

                If grdRef.Rows.Count = 0 Or lblLevelCom.Text = "0" Then
                    'btnNext.Visible = False
                    'btnSave.Visible = False
                    btnReport.Visible = False
                Else
                    RiskSummary()
                    'btnNext.Visible = True
                    'btnSave.Visible = True
                    btnCancel.Visible = True
                    btnReport.Visible = True
                End If
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Try
            If grdRef.SelectedIndex = -1 Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & Resources.resMsgKYC.msgSelect & "')", True)
            Else
                ds.Tables("dsCustomerCom").Rows(grdRef.SelectedIndex).Delete()
                ds.AcceptChanges()

                grdRef.DataSource = ds.Tables("dsCustomerCom")
                grdRef.DataBind()
                setGrid()

                grdRef.SelectedIndex = -1
                btnDelete.Attributes.Clear()

                If grdRef.Rows.Count = 0 Or lblLevelCom.Text = "" Or lblLevelCom.Text = "0" Then
                    'btnSave.Visible = False
                    'btnNext.Visible = False
                    btnReport.Visible = False

                    txtRiskLevel.Text = ""
                    lblOverview.Text = 0
                    txtReason.Text = ""
                    txtRiskLevel.BackColor = Drawing.Color.White
                Else
                    RiskSummary()
                End If
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

#End Region

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Try

            'If CInt(lblOverview.Text) > 1 Then
            If checkApprove() = False Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & strMsg & "')", True)
                Exit Sub
            End If
            'End If

            If Not Session("KYC") = 3 Then
                If ds.Tables("dsCustomerCom").Rows.Count = 0 Then
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & Resources.resMsgAlertKYC.NotRef & "')", True)
                    Exit Sub
                Else

                    If Not (chkCardIdDuplicate(txtBizNo.Text.Trim)) Then
                        strMsg = "ข้อมูลนิติบุคคลและข้อมูลผู้ที่เกี่ยวข้องซ้ำกัน"
                        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & strMsg & "')", True)
                        Exit Sub
                    End If

                End If
            End If

            If TypeKYC = 1 Then
                SaveNew()
                SaveLog(3)
            ElseIf TypeKYC = 2 Then
                saveUpdate()
                SaveLog(4)
            End If

            Session("strReason") = Nothing
            'Response.Redirect("NonIndividualSearch.aspx?KYC=" & Session("KYC") & "&CustSeq=" & Session("CUSTSEQ") & "")
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "message", _
                        "alert('" + Resources.resMsgKYC.msgSave + "');location.href = 'NonIndividualSearch.aspx?KYC=" & Session("KYC") & "&CUSTSEQ=" & Session("CUSTSEQ") & "';", True)
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

    Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click
        Try

            If CInt(lblOverview.Text) > 1 Then
                If checkApprove() = False Then
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & strMsg & "')", True)
                    Exit Sub
                End If
            End If

            If Not Session("KYC") = 3 Then
                If ds.Tables("dsCustomerCom").Rows.Count = 0 Then
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & Resources.resMsgAlertKYC.NotRef & "')", True)
                    Exit Sub
                End If
            End If

            If TypeKYC = 1 Then
                SaveNew()
                SaveLog(3)
            ElseIf TypeKYC = 2 Then
                saveUpdate()
                SaveLog(4)
            End If

            Session("strReason") = Nothing
            Response.Redirect("NonIndividualKYC.aspx?KYC=" & Session("KYC") & "&CUSTSEQ=" & CustSeq & "&CDD=" & lblOverview.Text & "&TypeKYC=" & TypeKYC & "")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try

    End Sub

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Try
            Session("TypeKYC") = Nothing
            Session("CustSeq") = Nothing
            Response.Redirect("NonIndividualSearch.aspx?KYC=" & Session("KYC") & "&CustSeq=" & CustSeq & "")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

    Protected Sub btnKYC_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnKYC.Click
        Try
            SaveLog(1)

            If CInt(Session("KYC")) = 1 Or CInt(Session("KYC")) = 3 Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "window.open('../Form/KYC1T_02.aspx?CUSTSEQ=" & CInt(CustSeq) & "&Type=" & CInt(Session("KYC")) & "','_blank','scrollbars=1,Width:800px, Height:600px')", True)
            ElseIf CInt(Session("KYC")) = 2 Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "window.open('../Form/KYC2T_02.aspx?CUSTSEQ=" & CInt(CustSeq) & "','_blank','scrollbars=1,Width:800px, Height:600px')", True)

            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub
    Public Function ValidateAcc() As Boolean
        Dim result As Boolean = True
        strMsg = ""
        'If grdRef.Rows.Count < 1 Then
        '    result = False
        '    strMsg &= " กรุณาระบุผู้เกี่ยวข้อง " & "\n"
        'End If

        'If rdoAcc.SelectedIndex = -1 Then
        '    result = False
        '    strMsg &= " กรุณาเลือกบัญชี " & "\n"
        'End If
        'If rdoAcc.SelectedIndex = 1 Then
        '    If ddlAcc.SelectedIndex = 0 Then
        '        result = False
        '        strMsg &= " กรุณาเลือกเลขที่บัญชี " & "\n"

        '    End If
        'End If


        If Not IsNumeric(txtSalaryPerMonth.Text) Then
            result = False
            strMsg &= " ระบุเงินเดือนไม่ถูกต้อง " & "\n"
        End If

        Return result
    End Function
    Protected Sub btnReport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReport.Click
        Try
            Dim intANSWERTYPE As Integer = 0
            If Request.QueryString("KYC") = 1 Then
                intANSWERTYPE = 2
            ElseIf Request.QueryString("KYC") = 2 Then
                intANSWERTYPE = 4
            ElseIf Request.QueryString("KYC") = 3 Then
                intANSWERTYPE = 6
            ElseIf Request.QueryString("KYC") = 4 Then
                intANSWERTYPE = 0
            End If

            If rdoAcc.SelectedIndex = 0 Then
                clsSessionMenuRight = Session("clsMenuRight")
                If Not TypeKYC = 1 Then

                    Dim qryRKYc = From tblKYC In KYCEntity.RKYC _
                                           Where tblKYC.CUSTSEQ = CustSeq And _
                                                 tblKYC.UPDATEBY = clsSessionMenuRight.getUserName And tblKYC.ACCOUNTNO = Nothing _
                                           Select tblKYC.ANSWERTYPE, tblKYC.ACCOUNTNO

                    If Not intANSWERTYPE = 0 Then
                        qryRKYc = qryRKYc.Where(Function(fn) fn.ANSWERTYPE = intANSWERTYPE)
                    End If



                    If qryRKYc.Count = 0 Then
                        hdfChkNewAcc.Value = 0
                    Else
                        hdfChkNewAcc.Value = 1
                    End If
                Else
                    hdfChkNewAcc.Value = 0
                End If

            End If
            If hdfChkNewAcc.Value = "" Then
                hdfChkNewAcc.Value = "0"
            End If

            ''''Prachak  ! Why do they created Account no by this process ??? ''''''''''''''''''''''''''''''''''''''''
            ''If Not hdfChkNewAcc.Value = enmStatusNewAcc.NoHaveNewAcc Then
            ''    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & "ได้มีการสร้างบัญชีไว้แล้วกรุณาไปหน้าข้อมูลKYC" & "')", True)
            ''    Exit Sub
            ''End If

            ''''Prachak ''''''''''''''''''''''''''''''''
            If Validate_For_All() = False Then Exit Sub
            ''''''''''''''''''''''''''''''''''''''''''''

            If checkApprove() = False Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & strMsg & "')", True)
                Exit Sub
            End If

            If Not ValidateAcc() Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & strMsg & "')", True)
                Exit Sub
            End If

            ''''Prachak ''''''''''''''''''''''''''''''''''''''''''''''''''''''
            ''Session("strReason") = txtReasonOverview.Text
            ''ScriptManager.RegisterStartupScript(Me, Me.GetType(), "message", _
            ''"alert('" + Resources.resMsgKYC.msgSave + "')", True)


            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "window.showModalDialog('../Form/KYCResultBiz.aspx?uniqueID=" & txtBizNo.Text.Trim & "&" _
                                               & "BizType=" & ddlBizType.Text & "&" _
                                               & "PrefixTH=" & ddlPrefix.Text & "&" _
                                               & "NameTh1=" & txtNameTH.Text.Trim & "&" _
                                               & "NameEN1=" & txtNameEN.Text.Trim & "&" _
                                               & "Nationality=" & ddlNationality.Text & "&" _
                                               & "Business1=" & ddlBusiness1.Text & "&" _
                                               & "BizOther1=" & txtBizOther1.Text.Trim & "&" _
                                               & "Des1=" & txtDes1.Text.Trim & "&" _
                                               & "Business2=" & ddlBusiness2.Text & "&" _
                                               & "BizOther2=" & txtBizOther2.Text.Trim & "&" _
                                               & "Des2=" & txtDes2.Text.Trim & "&" _
                                               & "Business3=" & ddlBusiness3.Text & "&" _
                                               & "BizOther3=" & txtBizOther3.Text.Trim & "&" _
                                               & "Des3=" & txtDes3.Text.Trim & "&" _
                                               & "IncomeSource1=" & ddlIncomeSource1.Text & "&" _
                                               & "IncomeSource2=" & ddlIncomeSource2.Text & "&" _
                                               & "IncomeSource3=" & ddlIncomeSource3.Text & "&" _
                                               & "RiskLevel=" & txtBizRiskLevel.Text.Trim & "'" _
                                               & ", null, 'status:no; dialogWidth:1000px; dialogHeight:600px; help:no; scroll:yes; menubar:no; resizable:no')", True)


            SaveLog(2)
            If TypeKYC = 1 Then
                SaveNew()
                Session("TypeKYC") = 2
                SaveLog(3)


            ElseIf TypeKYC = 2 Then
                saveUpdate()
                SaveLog(4)
            End If

            lblLevelComOld.Text = lblLevelCom.Text
            lblRiskNow.Text = "ความเสี่ยงล่าสุด : " + CStr(lblLevelCom.Text)
            lblRiskNow.Visible = True

            lblOverview.Text = lblLevelCom.Text 'ระดับความเสี่ยง

            If lblLevelCom.Text = 1 Then
                lblRiskNow.ForeColor = Drawing.Color.Green
            ElseIf lblLevelCom.Text = 2 Then
                lblRiskNow.ForeColor = Drawing.Color.Orange
            ElseIf lblLevelCom.Text = 3 Then
                lblRiskNow.ForeColor = Drawing.Color.Red
            End If
            btnHistory.Visible = True
            ''''Prachak '''''''''''''''
            Me.btnReport.Visible = False

            ''''Prachak '''''''''''''''
            ''''clear panel Approve''''
            If CInt(lblLevelCom.Text) = 3 Then
                PanelApprove.Enabled = False
                Me.ddlApprove.SelectedIndex = -1 : Me.Image10.Visible = False
                Me.txtApproveNo.Text = "" : Me.Image12.Visible = False
                Me.txtApprovePassword.Text = ""
                Me.txtDApproveDate.Text = "" : Me.Image13.Visible = False
            End If



        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, _
                                                            UpdatePanel1.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

#End Region

#Region "Function"

    Private Sub setGrid()
        'If Not grdRef.Rows.Count = 0 Then
        '    grdRef.HeaderRow.Cells(7).Visible = False
        '    For i As Integer = 0 To grdRef.Rows.Count - 1
        '        grdRef.Rows(i).Cells(7).Visible = False
        '    Next
        'End If
    End Sub

    Private Sub loadDataToDropDown()
        Try
            Dim clsDropDown As New clsMasterDropDown

            clsDropDown.setSubTypeToDdl(ddlBizType)
            clsDropDown.setPrefixTHToDdl(ddlPrefix, 2)
            clsDropDown.setNationalityToDdl(ddlNationality)
            clsDropDown.setBusinessToDdl(ddlBusiness1)
            clsDropDown.setBusinessToDdl(ddlBusiness2)
            clsDropDown.setBusinessToDdl(ddlBusiness3)
            clsDropDown.setCountyToDdl(ddlIncomeSource1)
            clsDropDown.setCountyToDdl(ddlIncomeSource2)
            clsDropDown.setCountyToDdl(ddlIncomeSource3)
            clsDropDown.setApproveToDdl(ddlApprove)

            ''''Prachak ''''''''''''''''
            clsDropDown.setPrefixTHToDdl(Me.ddlPrefixTH_POLITIC, 1)
            clsDropDown.setPrefixENToDdl(Me.ddlPrefixEN_POLITIC, 1)

            ''''Prachak ''''''''''''''''''''''
            clsDropDown.setProvince(Me.ddlFormalProvince)
            clsDropDown.setProvince(Me.ddlWORKPROVINCE)

            ''''Prachak ''''''''''''''''''''''
            clsDropDown.setOtherDoc_To_Ddl(Me.DdOtherID)
            clsDropDown.setOtherDoc_To_Ddl(Me.ddlOTH_ID_BO)
            clsDropDown.setPrefixTHToDdl(Me.ddlPrefixTH_BO, 1)
            clsDropDown.setPrefixENToDdl(Me.ddlPrefixEN_BO, 1)
            ''''Prachak '''''''''''''''''''''''''''''''''''
            clsDropDown.setMProductToDdl(Me.ddlPRODUCT_NAME)
            clsDropDown.setMAdditional_Service_To_Ddl(Me.ddlADDED_SERVICE)

            ddlIncomeSource1.SelectedValue = 202

            clsDropDown = Nothing

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Protected Sub ddlPrefixTH_POLITIC_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlPrefixTH_POLITIC.SelectedIndexChanged
        Me.ddlPrefixEN_POLITIC.SelectedValue = Me.ddlPrefixTH_POLITIC.SelectedValue
    End Sub

    Protected Sub ddlPrefixEN_POLITIC_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlPrefixEN_POLITIC.SelectedIndexChanged
        Me.ddlPrefixTH_POLITIC.SelectedValue = Me.ddlPrefixEN_POLITIC.SelectedValue
    End Sub

    Private Sub AutoInput()
        Try
            txtBizNo.Text = Request.QueryString("BIZCODE").Replace("*", "").Trim
            txtNameTH.Text = Request.QueryString("NAMETH").Replace("*", "").Trim
            txtNameEN.Text = Request.QueryString("NAMEEN").Replace("*", "").Trim
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub loadDataAddr_formal(ByVal province As String, ByVal amphor As String, ByVal tambol As String)
        Dim clsDropDown As New clsMasterDropDown

        If province = "" Then
            clsDropDown.setProvince(ddlFormalProvince)
        Else
            clsDropDown.setProvince(ddlFormalProvince, province)
            If Not (ddlFormalProvince.SelectedIndex = 0) Then
                clsDropDown.setAmphor(ddlFormalAmphor, province, amphor)

            End If
            If Not (ddlFormalProvince.SelectedIndex = 0) Then
                clsDropDown.setTambol(ddlFormalTambol, amphor, tambol)
            End If

        End If

    End Sub

    Private Sub loadDataAddr_Work(ByVal province As String, ByVal amphor As String, ByVal tambol As String)
        Dim clsDropDown As New clsMasterDropDown

        If province = "" Then
            clsDropDown.setProvince(ddlWORKPROVINCE)
        Else
            clsDropDown.setProvince(ddlWORKPROVINCE, province)
            If Not (ddlWORKPROVINCE.SelectedIndex = 0) Then
                clsDropDown.setAmphor(ddlWORKAMPHOR, province, amphor)
            End If
            If Not (ddlWORKPROVINCE.SelectedIndex = 0) Then
                clsDropDown.setTambol(ddlWORKTAMBOL, amphor, tambol)
            End If

        End If



    End Sub

    Private Sub BindingData()
        Dim clsMoney As New clsMoney
        Try
            Dim qryKYC = (From cust In KYCEntity.MCUSTOMER
                           Where cust.CUSTSEQ = CustSeq
                          Select cust).ToList

            If qryKYC(0).CUSTCODE = Nothing Then
                lblCustCode.Text = "เลขประจำตัวลูกค้า : -"
            Else
                lblCustCode.Text = "เลขประจำตัวลูกค้า : " + qryKYC(0).CUSTCODE.ToString
            End If

            hdfApprCode_MCus.Value = qryKYC(0).APPROVECODE.ToString
            txtReasonApp.Text = qryKYC(0).APPROVEREASON
            If Not hdfApprCode_MCus.Value = Nothing Then
                If hdfApprCode_MCus.Value = 1 Then
                    panelReasonApp.Visible = True
                End If
            End If

            If Not qryKYC(0).TRANTYPE Is Nothing Then
                ddlTranType.SelectedValue = qryKYC(0).TRANTYPE
                If qryKYC(0).TRANTYPE = 1 Then
                    ddlTranType.Enabled = False
                End If
            End If


            '''''''Prachak ''''''''''''''''''''''''''''''''''
            Me.lblCIF_CBS_NO.Text = qryKYC(0).CIF_CBS_NO
            Me.txtCIF_FDR_NO.Text = qryKYC(0).CIF_FDR_NO
            Me.txtCIF_NPA_NO.Text = qryKYC(0).CIF_NPA_NO

            Me.lblF_POLITIC.Text = qryKYC(0).F_POLITIC
            If Me.lblF_POLITIC.Text = "Y" Then
                Me.optPOL_CONNECT_Y.Checked = True
                Me.Set_Enable_Politic_True()
            Else
                Me.optPOL_CONNECT_N.Checked = True
                Me.Set_Enable_Politic_False()
            End If
            ''''''''''''''''''''''''''''''''''''
            If Not qryKYC(0).TYPEEVIDENCE Is Nothing Then
                DdOtherID.SelectedValue = qryKYC(0).TYPEEVIDENCE
            End If
            Me.txtTAX_ID.Text = qryKYC(0).TAX_ID

            If Not qryKYC(0).FILTER_RESULT Is Nothing Then
                Me.lblFILTER_RESULT_CUST.Text = qryKYC(0).FILTER_RESULT
            End If

            If Not qryKYC(0).RISK_LEVEL Is Nothing Then
                Me.lblRISK_LEVEL_CUST.Text = qryKYC(0).RISK_LEVEL
            End If
            Me.txtFORMALADDR.Text = qryKYC(0).FORMALADDR
            Me.txtFormalMoo.Text = qryKYC(0).FORMALMOO
            Me.txtFormalStreetDesc.Text = qryKYC(0).FORMALSTREETDESC
            Me.txtFormalSoiDESC.Text = qryKYC(0).FORMALSOIDESC
            Me.txtFormalBuilding.Text = qryKYC(0).FORMALBUILDING
            Me.txtFORMALZIP.Text = qryKYC(0).FORMALZIP
            Me.txtFormalPhone1.Text = qryKYC(0).FORMALPHONE1
            Me.txtFormalPhone2.Text = qryKYC(0).FORMALPHONE2
            Me.txtFormalPhone3.Text = qryKYC(0).FORMALPHONE3
            Me.txtFormalFax1_1.Text = qryKYC(0).FORMALFAX

            loadDataAddr_formal(qryKYC(0).FORMALPROVINCE, qryKYC(0).FORMALAMPHOR, qryKYC(0).FORMALTAMBOL)

            Me.txtWORKADDR.Text = qryKYC(0).WORKADDR
            Me.txtWORKMOO.Text = qryKYC(0).WORKMOO
            Me.txtWORKSTREETDESC.Text = qryKYC(0).WORKSTREETDESC
            Me.txtWORKSOIDESC.Text = qryKYC(0).WORKSOIDESC
            Me.txtWORKLOCALITY.Text = qryKYC(0).WORKLOCALITY
            Me.txtWORKZIP.Text = qryKYC(0).WORKZIP
            Me.txtWORKPHONE1.Text = qryKYC(0).WORKPHONE1
            Me.txtWORKPHONE2.Text = qryKYC(0).WORKPHONE2
            Me.txtWORKPHONE3.Text = qryKYC(0).WORKPHONE3
            Me.txtWORKFAX.Text = qryKYC(0).WORKFAX

            loadDataAddr_Work(qryKYC(0).WORKPROVINCE, qryKYC(0).WORKAMPHOR, qryKYC(0).WORKTAMBOL)



            Me.txtTYPEEVIDENCE_NO.Text = qryKYC(0).TYPEEVIDENCE_NO
            Me.lbBIRTH_DATE_TH.Text = qryKYC(0).BIRTH_DATE_TH
            Me.txtBIRTH_DATE_TH_DD.Text = (Mid(Me.lbBIRTH_DATE_TH.Text, 1, 2))
            Me.txtBIRTH_DATE_TH_MM.Text = (Mid(Me.lbBIRTH_DATE_TH.Text, 4, 2))
            Me.txtBIRTH_DATE_TH_YYYY.Text = (Mid(Me.lbBIRTH_DATE_TH.Text, 7, 4))


            Me.lbBIRTH_DATE_EN.Text = qryKYC(0).BIRTH_DATE_EN
            Me.txtBIRTH_DATE_EN_DD.Text = (Mid(Me.lbBIRTH_DATE_EN.Text, 1, 2))
            Me.txtBIRTH_DATE_EN_MM.Text = (Mid(Me.lbBIRTH_DATE_EN.Text, 4, 2))
            Me.txtBIRTH_DATE_EN_YYYY.Text = (Mid(Me.lbBIRTH_DATE_EN.Text, 7, 4))


            Me.txtOTH_NAT_ADD_1.Text = qryKYC(0).OTH_NAT_ADD_1
            Me.txtOTH_NAT_ADD_2.Text = qryKYC(0).OTH_NAT_ADD_2
            Me.txtOTH_NAT_ZIP.Text = qryKYC(0).OTH_NAT_ZIP
            Me.txtOTH_NAT_STREET.Text = qryKYC(0).OTH_NAT_STREET
            Me.txtOTH_NAT_PHN.Text = qryKYC(0).OTH_NAT_PHN
            Me.txtOTH_NAT_PHN_EXT.Text = qryKYC(0).OTH_NAT_PHN_EXT
            Me.txtOTH_NAT_MOBILE.Text = qryKYC(0).OTH_NAT_MOBILE
            Me.txtOTH_NAT_FAX.Text = qryKYC(0).OTH_NAT_FAX
            Me.txtOTH_NAT_EMAIL.Text = qryKYC(0).OTH_NAT_EMAIL

            ''''รายได้เฉลี่ยต่อเดือน '''''''''''''''''''''''''''''''''''''''''''''
            If Not qryKYC(0).AVR_REVENUE Is Nothing Then
                Me.ddlAVR_REVENUE.SelectedValue = qryKYC(0).AVR_REVENUE
            End If
            ''''ค่าใช้จ่ายเฉลี่ยต่อเดือน''''''''''''''''''''''''''''''''''''''''''''
            If Not qryKYC(0).AVR_EXPENSE Is Nothing Then
                Me.ddlAVR_EXPENSE.SelectedValue = qryKYC(0).AVR_EXPENSE
            End If
            ''''Product''''''''''''''''''''''''''''''''''''''''''''
            'If Not qryKYC(0).PRODUCT_NAME Is Nothing Then
            '    Me.ddlPRODUCT_NAME.SelectedValue = qryKYC(0).PRODUCT_NAME
            'End If

            ''''Additional Service''''''''''''''''''''''''''''''''''''''''''''
            'If Not qryKYC(0).ADDITIONAL_SERVICE Is Nothing Then
            '    Me.ddlADDITIONAL_SERVICE.SelectedValue = qryKYC(0).ADDITIONAL_SERVICE
            'End If
            '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

            txtBizNo.Text = qryKYC(0).UNIQUEID
            If Not qryKYC(0).CUSTSUBTYPE Is Nothing Then
                ddlBizType.SelectedValue = qryKYC(0).CUSTSUBTYPE
            End If
            If Not qryKYC(0).THPREFIX Is Nothing Then
                ddlPrefix.SelectedValue = qryKYC(0).THPREFIX
            End If
            txtNameTH.Text = qryKYC(0).THFIRSTNAME
            txtNameEN.Text = qryKYC(0).ENFIRSTNAME


            If Not qryKYC(0).NATIONALITY Is Nothing Then
                ddlNationality.SelectedValue = qryKYC(0).NATIONALITY
                Me.SElect_Risk_For_Nation()
                If ddlNationality.SelectedValue <> 202 Then
                    Me.Set_Enable_Oth_Nat_Address_True()
                Else
                    Me.Set_Enable_Oth_Nat_Address_False()
                End If
            End If

            'If Not qryKYC(0).BIZTYPE1 Is Nothing Then
            '    ddlBusiness1.SelectedValue = qryKYC(0).BIZTYPE1
            'End If

            txtBizOther1.Text = qryKYC(0).BIZTYPEOTHER1
            If Not qryKYC(0).BIZTYPE2 Is Nothing Then
                ddlBusiness2.SelectedValue = qryKYC(0).BIZTYPE2
            End If
            txtBizOther2.Text = qryKYC(0).BIZTYPEOTHER2
            If Not qryKYC(0).BIZTYPE3 Is Nothing Then
                ddlBusiness3.SelectedValue = qryKYC(0).BIZTYPE3
            End If
            txtBizOther3.Text = qryKYC(0).BIZTYPEOTHER3
            txtDes1.Text = qryKYC(0).BIZDESC1
            txtDes2.Text = qryKYC(0).BIZDESC2
            txtDes3.Text = qryKYC(0).BIZDESC3

            'If Not qryKYC(0).INCOMESOURCE1 Is Nothing Then
            '    ddlIncomeSource1.SelectedValue = qryKYC(0).INCOMESOURCE1
            'End If

            'If Not qryKYC(0).INCOMESOURCE2 Is Nothing Then
            '    ddlIncomeSource2.SelectedValue = qryKYC(0).INCOMESOURCE2
            'End If
            'If Not qryKYC(0).INCOMESOURCE3 Is Nothing Then
            '    ddlIncomeSource3.SelectedValue = qryKYC(0).INCOMESOURCE3
            'End If

            autoBizType()

            If Not qryKYC(0).NGOCHECK1 Is Nothing Then
                If qryKYC(0).NGOCHECK1 = 1 Then
                    chkNGO.Items(0).Selected = True
                ElseIf qryKYC(0).NGOCHECK1 = 2 Then
                    chkNGO.Items(1).Selected = True
                End If
            End If

            If Not qryKYC(0).COMPCHECK1 Is Nothing Then
                If qryKYC(0).COMPCHECK1 = 1 Then
                    chkRegister.Items(0).Selected = True
                ElseIf qryKYC(0).COMPCHECK1 = 2 Then
                    chkRegister.Items(1).Selected = True
                ElseIf qryKYC(0).COMPCHECK1 = 3 Then
                    chkRegister.Items(2).Selected = True
                End If
            End If

            If Not qryKYC(0).SALARYPERMONTH Is Nothing Then
                txtSalaryPerMonth.Text = clsMoney.insertComma(qryKYC(0).SALARYPERMONTH)
            Else
                txtSalaryPerMonth.Text = "0"
            End If
            If Not qryKYC(0).ISANSWERSALARY Is Nothing Then
                rdoAnsSalary.SelectedValue = qryKYC(0).ISANSWERSALARY.ToString
                If rdoAnsSalary.SelectedValue = "0" Then
                    txtSalaryPerMonth.Enabled = False
                Else
                    txtSalaryPerMonth.Enabled = True
                End If
            Else
                rdoAnsSalary.SelectedValue = "0"
                txtSalaryPerMonth.Enabled = False
            End If

            If Not qryKYC(0).AMLCDDOVERVIEW Is Nothing Then
                txtRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ " + CStr(qryKYC(0).AMLCDDOVERVIEW)
            End If

            If Not qryKYC(0).AMLCDD Is Nothing Then
                If Not qryKYC(0).AMLCDD = 0 Then
                    lblLevelComOld.Text = qryKYC(0).AMLCDD
                    lblRiskNow.Text = "ความเสี่ยงล่าสุด : " + CStr(qryKYC(0).AMLCDD)
                    lblRiskNow.Visible = True

                    lblOverview.Text = qryKYC(0).AMLCDD 'ระดับความเสี่ยง

                    If qryKYC(0).AMLCDD = 1 Then
                        lblRiskNow.ForeColor = Drawing.Color.Green
                    ElseIf qryKYC(0).AMLCDD = 2 Then
                        lblRiskNow.ForeColor = Drawing.Color.Orange
                    ElseIf qryKYC(0).AMLCDD = 3 Then
                        lblRiskNow.ForeColor = Drawing.Color.Red
                    End If
                Else
                    lblLevelComOld.Text = 0
                    btnHistory.Visible = False
                End If

            Else
                lblLevelComOld.Text = 0
                btnHistory.Visible = False
            End If

            txtReasonSAS.Text = qryKYC(0).AMLREASONSAS
            If Not qryKYC(0).AMLCDDSAS Is Nothing Then
                hdfAML.Value = qryKYC(0).AMLCDDSAS
            End If


            qryKYC = Nothing


        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub BindingAcc(ByVal intCusSeq As Integer)
        Try
            clsDataTable = New clsLINQToDataTable

            Dim intANSWERTYPE As Integer = 0

            If Request.QueryString("KYC") = 1 Then
                intANSWERTYPE = 2
            ElseIf Request.QueryString("KYC") = 2 Then
                intANSWERTYPE = 4
            ElseIf Request.QueryString("KYC") = 3 Then
                intANSWERTYPE = 6
            ElseIf Request.QueryString("KYC") = 4 Then
                intANSWERTYPE = 0
            End If


            If ds.Tables.Contains("ShowAccAll") Then
                ds.Tables.Remove("ShowAccAll")
            End If

            Dim qryKYCAcc = From KYCAcc In KYCEntity.RKYC Where KYCAcc.CUSTSEQ = intCusSeq And Not (KYCAcc.ACCOUNTNO = Nothing)

            If Not intANSWERTYPE = 0 Then
                qryKYCAcc = qryKYCAcc.Where(Function(fn) fn.ANSWERTYPE = intANSWERTYPE)
            End If

            ds.Tables.Add(clsDataTable.LINQToDataTable(qryKYCAcc, "ShowAccAll").Copy)
            ''grdShowAccount.DataSource = ds.Tables("ShowAccAll")
            ''grdShowAccount.DataBind()
        Catch ex As Exception
            Throw ex
        End Try

    End Sub

#Region "Function Drop Drown"

    Private Sub indexBizChanging1()
        If Not ddlBusiness1.SelectedValue = "" Then
            If ddlBusiness1.SelectedValue = 99 Then
                txtBizOther1.Visible = True
                lblOther12.Visible = True
            Else
                txtBizOther1.Visible = True
                txtBizOther1.Text = ""
                lblOther12.Visible = True
            End If
        Else
            txtBizOther1.Visible = True
            txtBizOther1.Text = ""
            lblOther12.Visible = True
        End If
    End Sub

    Private Sub indexBizChanging2()
        If Not ddlBusiness2.SelectedValue = "" Then
            If ddlBusiness2.SelectedValue = 99 Then
                txtBizOther2.Visible = True
                lblOther22.Visible = True
            Else
                txtBizOther2.Visible = False
                txtBizOther2.Text = ""
                lblOther22.Visible = False
            End If
        Else
            txtBizOther2.Visible = False
            txtBizOther2.Text = ""
            lblOther22.Visible = False
        End If

    End Sub

    Private Sub indexBizChanging3()

        If Not ddlBusiness3.SelectedValue = "" Then
            If ddlBusiness3.SelectedValue = 99 Then
                txtBizOther3.Visible = True
                lblOther32.Visible = True
            Else
                txtBizOther3.Visible = False
                txtBizOther3.Text = ""
                lblOther32.Visible = False
            End If
        Else
            txtBizOther3.Visible = False
            txtBizOther3.Text = ""
            lblOther32.Visible = False
        End If

    End Sub

    Private Sub autoBizType()
        If Not ddlBizType.SelectedValue Is DBNull.Value Then
            If Not ddlBizType.SelectedIndex = 0 Then
                If ddlBizType.SelectedValue = 3 Then
                    chkNGO.Enabled = True
                    chkRegister.Enabled = False
                    chkRegister.Items(0).Selected = False
                    chkRegister.Items(1).Selected = False
                    chkRegister.Items(2).Selected = False
                    hdfEnable.Value = 1

                Else
                    chkRegister.Enabled = True
                    chkNGO.Enabled = False
                    chkNGO.Items(0).Selected = False
                    chkNGO.Items(1).Selected = False
                    hdfEnable.Value = 2
                End If
            End If


        End If

    End Sub

#End Region

    Private Sub createStructure()
        Try
            clsLINQToDataTable = New clsLINQToDataTable
            clsDatabase = New clsDatabase

            If ds.Tables.Contains("dsCustomerCom") Then
                ds.Tables.Remove("dsCustomerCom")
            End If

            If TypeKYC = 1 Then
                Dim sql As String = "select * from MCUSTOMER m" _
                                    & " join MCOMPRELATION r on r.REFCUSTSEQ = m.CUSTSEQ" _
                                    & " join MPOSITION p on r.POCODE = p.POCODE " _
                                    & " where m.custseq =0 "
                ds.Tables.Add(clsDatabase.QueryDataSet(sql, "dsCustomerCom").Tables("dsCustomerCom").Copy)
            ElseIf TypeKYC = 2 Then
                'Dim qryList = (From ref In KYCEntity.MCOMPRELATION
                '             Group Join c In KYCEntity.MCUSTOMER
                '             On ref.REFCUSTSEQ Equals c.CUSTSEQ Into refJoin = Group
                '             Group Join p In KYCEntity.MPOSITION
                '             On ref.POCODE Equals p.POCODE Into refP = Group
                '             From refCom In refJoin.DefaultIfEmpty
                '             Where (ref.CUSTSEQ = CustSeq)
                '             Select refCom.CUSTCODE, refCom.CUSTSEQ, refCom.CUSTTYPE, refCom.CUSTSUBTYPE,
                '             refCom.UNIQUEID, refCom.THPREFIX, refCom.THFIRSTNAME,
                '             refCom.THMIDNAME, refCom.THLASTNAME,
                '             refCom.ENPREFIX, refCom.ENFIRSTNAME, refCom.ENMIDNAME, refCom.ENLASTNAME,
                '             refCom.NATIONALITY, refCom.OCCUPATIONTYPE1,
                '             refCom.OCCUPATIONTYPEOTHER1, refCom.OCCUPATIONTYPE2,
                '             refCom.OCCUPATIONTYPEOTHER2, refCom.OCCUPATIONTYPE3,
                '             refCom.OCCUPATIONTYPEOTHER3, refCom.BIZTYPE1,
                '             refCom.BIZTYPEOTHER1, refCom.BIZTYPE2, refCom.BIZTYPEOTHER2,
                '             refCom.BIZTYPE3, refCom.BIZTYPEOTHER3, refCom.BIZDESC1,
                '             refCom.BIZDESC2, refCom.BIZDESC3,
                '             refCom.INCOMESOURCE1, refCom.INCOMESOURCE2, refCom.INCOMESOURCE3,
                '             refCom.AMLCDD, refCom.AMLREASON,
                '             refCom.CREATEBY, refCom.CREATEDATE, refCom.UPDATEBY, refCom.UPDATEDATE
                '            ).ToList()

                'Dim qryList = (From tbl In (From ref In KYCEntity.MCOMPRELATION
                '                            Group Join c In KYCEntity.MCUSTOMER
                '                            On ref.REFCUSTSEQ Equals c.CUSTSEQ Into refJoin = Group
                '                            From a In refJoin.DefaultIfEmpty
                '                            )
                '              Group Join p In KYCEntity.MPOSITION
                '              On tbl.ref.POCODE Equals p.POCODE Into refP = Group
                '              From refCom In refP.DefaultIfEmpty
                '              Where (tbl.ref.CUSTSEQ = CustSeq) And (tbl.ref.REFCUSTSEQ <> 0) And tbl.a.UNIQUEID IsNot Nothing
                '              Select tbl.a.CUSTCODE, tbl.a.CUSTSEQ, tbl.a.CUSTTYPE, tbl.a.CUSTSUBTYPE,
                '             tbl.a.CUSTIDTYPE, tbl.a.UNIQUEID, tbl.a.THPREFIX, tbl.a.THFIRSTNAME,
                '             tbl.a.THMIDNAME, tbl.a.THLASTNAME,
                '             tbl.a.ENPREFIX, tbl.a.ENFIRSTNAME, tbl.a.ENMIDNAME, tbl.a.ENLASTNAME,
                '             tbl.a.NATIONALITY, tbl.a.OCCUPATIONTYPE1,
                '             tbl.a.OCCUPATIONTYPEOTHER1, tbl.a.OCCUPATIONTYPE2,
                '             tbl.a.OCCUPATIONTYPEOTHER2, tbl.a.OCCUPATIONTYPE3,
                '             tbl.a.OCCUPATIONTYPEOTHER3, tbl.a.BIZTYPE1,
                '             tbl.a.BIZTYPEOTHER1, tbl.a.BIZTYPE2, tbl.a.BIZTYPEOTHER2,
                '             tbl.a.BIZTYPE3, tbl.a.BIZTYPEOTHER3, tbl.a.BIZDESC1,
                '             tbl.a.BIZDESC2, tbl.a.BIZDESC3,
                '             tbl.a.INCOMESOURCE1, tbl.a.INCOMESOURCE2, tbl.a.INCOMESOURCE3,
                '             tbl.a.NGOCHECK1, tbl.a.COMPCHECK1,
                '             tbl.a.AMLCDD, tbl.a.AMLREASON, tbl.a.AMLCDDOVERVIEW, tbl.a.AMLREASONOVERVIEW,
                '             tbl.a.CREATEBY, tbl.a.CREATEDATE, tbl.a.UPDATEBY, tbl.a.UPDATEDATE,
                '             tbl.a.DEPD, tbl.a.DEPL, tbl.a.DEPP, tbl.a.DEPN, tbl.a.DEPUPDATE, tbl.a.AMLREASONSAS, tbl.a.AMLCDDSAS,
                '             refCom.POCODE, refCom.PONAME).ToList
                'If qryList.Count = 0 Then
                '    Dim sql As String = "select * from MCUSTOMER m" _
                '                   & " join MCOMPRELATION r on r.REFCUSTSEQ = m.CUSTSEQ" _
                '                   & " join MPOSITION p on r.POCODE = p.POCODE " _
                '                   & " where m.custseq =0 "
                '    ds.Tables.Add(clsDatabase.QueryDataSet(sql, "dsCustomerCom").Tables("dsCustomerCom").Copy)
                'Else
                '    ds.Tables.Add(clsLINQToDataTable.LINQToDataTable(qryList, "dsCustomerCom").Copy)
                'End If

                'qryList = Nothing

                Dim sql As String = "select * from MCUSTOMER m" _
                                   & " join MCOMPRELATION r on r.REFCUSTSEQ = m.CUSTSEQ" _
                                   & " join MPOSITION p on r.POCODE = p.POCODE " _
                                   & " where m.custseq = 0 "
                ds.Tables.Add(clsDatabase.QueryDataSet(sql, "dsCustomerCom").Tables("dsCustomerCom").Copy)

                Dim dt_all = SearchData(Session("CUSTSEQ").ToString())

                For Each r In dt_all.Rows
                    Dim drCust As DataRow = ds.Tables("dsCustomerCom").NewRow
                    drCust("CustSEQ") = r("CUSTSEQ").ToString()
                    drCust("CreateBy") = DBNull.Value
                    drCust("CustType") = r("CUSTTYPE") ' 1 = บุคคลม 2 = นิติบุคคล
                    drCust("CustSubType") = 1
                    drCust("CUSTIDTYPE") = DBNull.Value
                    drCust("AMLCDD") = r("RISK_LEVEL").ToString()
                    drCust("AMLREASON") = ""
                    drCust("UNIQUEID") = r("UNIQUEID")
                    drCust("ThPreFix") = r("THPREFIX")
                    drCust("ThFirstName") = r("INDV_FIRST_NAME")
                    drCust("ThMidName") = ""
                    drCust("ThLastName") = r("INDV_LAST_NAME")
                    drCust("ENPreFix") = DBNull.Value
                    drCust("EnFirstName") = ""
                    drCust("EnMidName") = ""
                    drCust("EnLastName") = ""

                    drCust("POCODE") = r("GROUP_CODE").ToString + r("GROUP_CODE_SUB").ToString
                    drCust("PONAME") = r("GROUP_CODE_SUB_NAME")
                    ds.Tables("dsCustomerCom").Rows.Add(drCust)
                Next

                grdRef.DataSource = ds.Tables("dsCustomerCom")
                grdRef.DataBind()
            End If


            clsLINQToDataTable = Nothing
            clsDatabase = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Function checkApprove() As Boolean
        Try
            Dim result As Boolean = True

            ''''Prachak Oct 27, 2014
            If CInt(lblLevelCom.Text) = 3 Then
                PanelApprove.Enabled = True
            Else
                PanelApprove.Enabled = False
            End If


            If PanelApprove.Enabled = True Then
                If ddlApprove.SelectedIndex = 0 Then
                    result = False
                    Image10.ImageUrl = "~/img/icon/cancel.png"
                    Image10.Visible = True
                    strMsg = strMsg + Resources.resMsgAlertKYC.NotStatusApprove + "\n"
                ElseIf ddlApprove.SelectedValue = 2 Or ddlApprove.SelectedValue = 3 Then
                    Image10.ImageUrl = "~/img/icon/accept.png"
                    'If txtApprove.Text.Trim = "" Then
                    '    result = False
                    '    Image11.ImageUrl = "~/img/icon/cancel.png"
                    '    strMsg = strMsg + Resources.resMsgAlertKYC.NotApproveName + "\n"
                    'Else
                    '    Image11.ImageUrl = "~/img/icon/accept.png"
                    'End If

                    If txtApproveNo.Text.Trim = "" Then
                        result = False
                        Image12.ImageUrl = "~/img/icon/cancel.png"
                        strMsg = strMsg + Resources.resMsgAlertKYC.NotApproveNo + "\n"
                    Else
                        Dim clsCheckApprove As clsCheckApprove = New clsCheckApprove
                        Dim strApp As String = clsCheckApprove.checkRightApprove(txtApproveNo.Text, clsSessionMenuRight.getUserName, clsSessionMenuRight.getRoleGroup, clsSessionMenuRight.getBranchCode, clsSessionMenuRight.getZoneCode, clsSessionMenuRight.getDeptCode, txtApprovePassword.Text)

                        If strApp = "" Then
                            Image12.ImageUrl = "~/img/icon/accept.png"
                        Else
                            result = False
                            Image12.ImageUrl = "~/img/icon/cancel.png"
                            strMsg = strMsg + strApp + "\n"
                        End If
                    End If
                    If txtDApproveDate.Text = "" Then
                        result = False
                        Image13.ImageUrl = "~/img/icon/cancel.png"
                        strMsg = strMsg + Resources.resMsgAlertKYC.NotApproveDate + "\n"
                    Else
                        Image13.ImageUrl = "~/img/icon/accept.png"
                    End If

                    Image10.Visible = True
                    'Image11.Visible = True
                    Image12.Visible = True
                    Image13.Visible = True
                End If
            End If

            Return result
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Function checkBeforeCompile() As Boolean
        Try
            Dim result As Boolean = True
            clsCheckLanguage = New clsCheckLanguage
            clsCheckID = New clsCheckID

            If ddlTranType.SelectedIndex = 0 Then
                result = False
                Image14.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotTranType + "\n"
            Else
                Image14.ImageUrl = "~/img/icon/accept.png"
            End If

            If txtBizNo.Text = "" Then
                result = False
                Image1.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotBizID + "\n"
            Else
                If Not txtBizNo.Text = hdfUniqueID.Value Then
                    If clsCheckID.checkUniqueID2(txtBizNo.Text, TypeKYC, CustSeq) = False Then
                        result = False
                        Image1.ImageUrl = "~/img/icon/cancel.png"
                        clsCheckID = Nothing
                        strMsg = strMsg + Resources.resMsgAlertKYC.UniqueBizNo + "\n"
                    Else
                        Image1.ImageUrl = "~/img/icon/accept.png"
                    End If
                Else
                    Image1.ImageUrl = "~/img/icon/accept.png"
                End If

            End If
            If ddlBizType.SelectedValue Is DBNull.Value Then
                result = False
                Image2.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotBizType + "\n"
            ElseIf ddlBizType.SelectedIndex = 0 Then
                result = False
                Image2.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotBizType + "\n"
            ElseIf ddlBizType.SelectedValue = 2 Then
                If Not (ddlBusiness1.SelectedValue > 51 And ddlBusiness1.SelectedValue < 60) And Not (ddlBusiness2.SelectedValue > 51 And ddlBusiness2.SelectedValue < 60) And Not (ddlBusiness3.SelectedValue > 51 And ddlBusiness3.SelectedValue < 60) Or Not ddlTranType.SelectedValue = 3 Then
                    If Not txtBizNo.Text.Trim.Length = 13 Then
                        result = False
                        Image1.ImageUrl = "~/img/icon/cancel.png"
                        strMsg = strMsg + Resources.resMsgAlertKYC.CheckBizNo + "\n"
                    Else
                        Image2.ImageUrl = "~/img/icon/accept.png"
                    End If
                Else
                    Image2.ImageUrl = "~/img/icon/accept.png"
                End If

            Else
                Image2.ImageUrl = "~/img/icon/accept.png"
            End If

            If Me.lblFILTER_RESULT_CUST.Text = "" Then
                strMsg = strMsg + "ต้องตรวจกรองรายชื่อก่อนทำการประเมินความเสี่ยง" + "\n"
                result = False
                Image2.ImageUrl = "~/img/icon/cancel.png"
            Else
                Image2.ImageUrl = "~/img/icon/accept.png"
            End If

            ''''Prachak'''''''''''''''
            If CInt(Me.lblCount_Corp_Cate.Text) = 0 Then
                strMsg = strMsg + "ป้อนขัอมูลในตาราง-ประเภทธุรกิจ-ให้ครบถ้วน" + "\n"
                result = False
                Image2.ImageUrl = "~/img/icon/cancel.png"
            Else
                Image2.ImageUrl = "~/img/icon/accept.png"
            End If
            ''''''''''''''''''''''''''

            'If ddlPrefix.SelectedIndex = 0 Then
            '    result = False
            '    Image3.ImageUrl = "~/img/icon/cancel.png"
            '    strMsg = strMsg + Resources.resMsgAlertKYC.NotBizPrefix + "\n"
            'Else
            '    Image3.ImageUrl = "~/img/icon/accept.png"
            'End If

            'If Not ddlNationality.SelectedIndex = 0 Then
            '    If ddlNationality.SelectedValue = 202 Then
            '        If txtNameTH.Text = "" Then
            '            result = False
            '            Image4.ImageUrl = "~/img/icon/cancel.png"
            '            strMsg = strMsg + Resources.resMsgAlertKYC.NotBizTHName + "\n"
            '        Else
            '            Image4.ImageUrl = "~/img/icon/accept.png"
            '        End If
            '    End If
            'End If

            If txtNameEN.Text = "" Then
                result = False
                Image5.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotBizENName + "\n"
            ElseIf clsCheckLanguage.checkLanguageEN(txtNameEN.Text.Trim) = False Then
                strMsg = strMsg + Resources.resMsgKYC.msgEN + "\n"
                result = False
                Image5.ImageUrl = "~/img/icon/cancel.png"
            Else
                Image5.ImageUrl = "~/img/icon/accept.png"
            End If

            If ddlNationality.SelectedIndex = 0 Then
                result = False
                Image6.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotNationality + "\n"
            Else
                Image6.ImageUrl = "~/img/icon/accept.png"
            End If


            'If ddlBusiness1.SelectedIndex = 0 Then
            '    result = False
            '    Image7.ImageUrl = "~/img/icon/cancel.png"
            '    strMsg = strMsg + Resources.resMsgAlertKYC.NotBusiness + " 1" + "\n"
            'ElseIf ddlBusiness1.SelectedValue = 99 And txtBizOther1.Text.Trim = "" Then
            '    result = False
            '    Image7.ImageUrl = "~/img/icon/cancel.png"
            '    strMsg = strMsg + Resources.resMsgAlertKYC.NotBusinessOther + " 1" + "\n"
            'Else
            '    Image7.ImageUrl = "~/img/icon/accept.png"
            'End If
            If Not ddlBusiness2.SelectedIndex = 0 Then
                If ddlBusiness2.SelectedValue = 99 And txtBizOther2.Text.Trim = "" Then
                    result = False
                    Image7.ImageUrl = "~/img/icon/cancel.png"
                    strMsg = strMsg + Resources.resMsgAlertKYC.NotBusinessOther + " 2" + "\n"
                Else
                    Image7.ImageUrl = "~/img/icon/accept.png"
                End If
            End If
            If Not ddlBusiness3.SelectedIndex = 0 Then
                If ddlBusiness3.SelectedValue = 99 And txtBizOther3.Text.Trim = "" Then
                    result = False
                    Image7.ImageUrl = "~/img/icon/cancel.png"
                    strMsg = strMsg + Resources.resMsgAlertKYC.NotBusinessOther + " 3" + "\n"
                Else
                    Image7.ImageUrl = "~/img/icon/accept.png"
                End If
            End If

            If ddlIncomeSource1.SelectedIndex = 0 Then
                result = False
                Image8.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotIncomeSource + "\n"
            Else
                Image8.ImageUrl = "~/img/icon/accept.png"
            End If

            If chkRegister.Enabled = True Then
                ''''Prachak ''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                'If Not chkRegister.Items(0).Selected = True And Not chkRegister.Items(1).Selected = True And Not chkRegister.Items(2).Selected = True Then
                '    '   Image9.ImageUrl = "~/img/icon/accept.png"
                '    result = False
                '    Image9.ImageUrl = "~/img/icon/cancel.png"
                '    strMsg = strMsg + Resources.resMsgKYC.msgRegis + "\n"
                '    GoTo complete
                'Else
                '    If checkRegis() = True Then
                '        Image9.ImageUrl = "~/img/icon/accept.png"
                '    Else
                '        result = False
                '        Image9.ImageUrl = "~/img/icon/cancel.png"
                '        strMsg = strMsg + Resources.resMsgKYC.msgRegis + "\n"
                '        GoTo complete
                '    End If
                'End If
            Else
                Image9.ImageUrl = "~/img/icon/accept.png"
            End If

            If chkNGO.Enabled = True Then
                If chkNGO.Items(0).Selected = True And chkNGO.Items(1).Selected = True Then
                    result = False
                    Image9.ImageUrl = "~/img/icon/cancel.png"
                    strMsg = strMsg + Resources.resMsgKYC.msgNGO + "\n"
                Else
                    Image9.ImageUrl = "~/img/icon/accept.png"
                End If
            Else
                Image9.ImageUrl = "~/img/icon/accept.png"
            End If

complete:
            statusValidation()
            clsCheckID = Nothing
            clsCheckLanguage = Nothing

            Return result
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Private Function checkRegis() As Boolean
        Try
            Dim result As Boolean = True
            If chkRegister.Items(0).Selected = True And chkRegister.Items(1).Selected = True Then
                result = False
            ElseIf chkRegister.Items(0).Selected = True And chkRegister.Items(2).Selected = True Then
                result = False
            ElseIf chkRegister.Items(1).Selected = True And chkRegister.Items(2).Selected = True Then
                result = False
            End If

            Return result
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Private Sub statusValidation()

        Image1.Visible = True
        Image2.Visible = True
        Image3.Visible = True
        Image4.Visible = True
        Image5.Visible = True
        Image6.Visible = True
        Image7.Visible = True
        Image8.Visible = True
        Image9.Visible = True
        Image14.Visible = True
    End Sub

    Private Sub compileCDD()
        Try
            Dim strReason = ""
            Dim risk As Integer

            'risk = clsRiskLevel.riskLevel(txtBizNo.Text.Trim, txtNameTH.Text.Trim, "", "", txtNameEN.Text.Trim, "", "", 0, "", 0, "", 0, "", ddlBusiness1.SelectedValue, ddlBusiness1.SelectedItem.Text, ddlBusiness2.SelectedValue, ddlBusiness2.SelectedItem.Text, ddlBusiness3.SelectedValue, ddlBusiness3.SelectedItem.Text, ddlNationality.SelectedValue, ddlNationality.SelectedItem.Text, ddlIncomeSource1.SelectedValue, ddlIncomeSource1.SelectedItem.Text, ddlIncomeSource2.SelectedValue, ddlIncomeSource2.SelectedItem.Text, ddlIncomeSource3.SelectedValue, ddlIncomeSource3.SelectedItem.Text, strReason)
            'If Not chkNGO.SelectedIndex = -1 Then
            ''    risk = clsRiskLevel.checkNPO(risk, chkNGO.SelectedValue, strReason)
            ''End If
            ''If Not chkRegister.SelectedIndex = -1 Then
            ''    risk = clsRiskLevel.checkRegister(risk, chkRegister.SelectedValue, strReason)
            ''End If

            risk = clsRiskLevel.CalculateRisk(Convert.ToInt32(lblEVAL_Sanct_Score.Text) _
                                                      , Convert.ToInt32(lblEVAL_OCC_SCORE.Text) _
                                                      , Convert.ToInt32(lblEVAL_NATION_SCORE.Text) _
                                                      , Convert.ToInt32(lblEVAL_RESIDENT_SCORE.Text) _
                                                      , Convert.ToInt32(lblEVAL_INC_SOURCE_SCORE.Text) _
                                                      , Convert.ToInt32(lblEVAL_PRODUCT_SCORE.Text) _
                                                      , Convert.ToInt32(lblEVAL_ADD_SERV_SCORE.Text) _
                                                      , Convert.ToInt32(lblEVAL_BIZ_TRAN_SCORE.Text) _
                                                      )


            If Not Session("Sanction") = Nothing Then
                risk = 3
                strReason = clsRiskLevel.sumString(strReason, Session("Sanction"))
                Session("Sanction") = Nothing
            End If

            If risk = 1 Then
                txtRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ 1"
                ''''Prachak ''''''''''
                Me.txtBizRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ 1" : txtBizRiskLevel.BackColor = Drawing.Color.LawnGreen
                lblLevelCom.Text = 1
                txtReason.Text = ""
                txtRiskLevel.BackColor = Drawing.Color.LawnGreen
            ElseIf risk = 2 Then
                txtRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ 2"
                ''''Prachak ''''''''''
                Me.txtBizRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ 2" : txtBizRiskLevel.BackColor = Drawing.Color.Orange
                lblLevelCom.Text = 2
                txtReason.Text = strReason
                txtRiskLevel.BackColor = Drawing.Color.Orange
            ElseIf risk = 3 Then
                txtRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ 3"
                ''''Prachak ''''''''''
                Me.txtBizRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ 3" : txtBizRiskLevel.BackColor = Drawing.Color.OrangeRed
                lblLevelCom.Text = 3
                txtReason.Text = strReason
                txtRiskLevel.BackColor = Drawing.Color.OrangeRed
            End If

            ''''Prachak '''''''''''
            Me.Find_next_Review()
            ''''''''''''''''''''''''

            If grdRef.Rows.Count = 0 Or lblLevelCom.Text = "0" Then
                'btnNext.Visible = False
                'btnSave.Visible = False
                btnReport.Visible = False
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & Resources.resMsgKYC.msgLevel & risk & "')", True)
            Else
                'RiskSummary()
                'btnNext.Visible = True
                'btnSave.Visible = True
                btnCancel.Visible = True
                btnReport.Visible = True
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub RiskSummary() 'สรุปภาพรวมของความเสี่ยง

        Try
            Dim risk As Integer = lblLevelCom.Text
            Dim sumString As String = ""
            Dim refString As String = ""

            If Not txtReason.Text = "" Then
                sumString = txtReason.Text
            End If

            For i As Integer = 0 To ds.Tables("dsCustomerCom").Rows.Count - 1

                If Not CInt(ds.Tables("dsCustomerCom").Rows(i)("AMLCDD")) = 1 Then
                    risk = clsRiskLevel.updateRisk(risk, ds.Tables("dsCustomerCom").Rows(i)("AMLCDD"))
                    refString = ds.Tables("dsCustomerCom").Rows(i)("AMLREASON").ToString.Replace(vbCr, " (ผู้เกี่ยวข้อง)" + vbCr)
                    sumString = clsRiskLevel.sumString(sumString, refString + " (ผู้เกี่ยวข้อง)")
                End If

            Next

            If Not txtReasonSAS.Text = "" Then
                If hdfAML.Value > risk Then
                    risk = hdfAML.Value
                End If
            End If

            If risk = 1 Then
                txtBizRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ 1"
                txtReasonOverview.Text = ""
                txtBizRiskLevel.BackColor = Drawing.Color.LawnGreen
            ElseIf risk = 2 Then
                txtBizRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ 2"
                txtReasonOverview.Text = sumString
                txtBizRiskLevel.BackColor = Drawing.Color.Orange
            ElseIf risk = 3 Then
                txtBizRiskLevel.Text = "ลูกค้ามีความเสี่ยงระดับ 3"
                txtReasonOverview.Text = sumString
                txtBizRiskLevel.BackColor = Drawing.Color.OrangeRed
            End If

            lblOverview.Text = risk

            Dim convertDate As clsDateFormat = New clsDateFormat
            txtDApproveDate.Text = convertDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.Th, Now.Date)
            convertDate = Nothing

            If lblOverview.Text > 2 Then
                PanelApprove.Enabled = True
                panelReasonApp.Visible = True
            Else
                PanelApprove.Enabled = True
                panelReasonApp.Visible = True
            End If

            If TypeKYC = 2 Then 'กรณีลูกค้าเก่าเปิดบัญชีใหม่ เช็คความเสี่ยงว่าเปลียนแปลงหรือไม่
                If Not lblLevelComOld.Text = 0 Then
                    If risk = 3 Then
                        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & Resources.resMsgKYC.msgLevelOverview & risk & " " & Resources.resMsgKYC.msgLevelUp & "')", True)
                        PanelApprove.Enabled = True
                        panelReasonApp.Visible = True
                        sumString = clsRiskLevel.sumString(sumString, "- " + Resources.resMsgKYC.msgLevelUp)
                        txtReasonOverview.Text = sumString
                    ElseIf CInt(lblLevelComOld.Text) = 3 Then '
                        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & Resources.resMsgKYC.msgLevelOverview & risk & " " & Resources.resMsgKYC.msgLevelDown & "')", True)
                        PanelApprove.Enabled = True
                        panelReasonApp.Visible = True
                        sumString = clsRiskLevel.sumString(sumString, "- " + Resources.resMsgKYC.msgLevelDown)
                        txtReasonOverview.Text = sumString
                        '    ElseIf risk > CInt(lblLevelComOld.Text) Then '
                        '   ElseIf risk < CInt(lblLevelComOld.Text) Then

                    Else 'ความเสี่ยงเท่าเดิม
                        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & Resources.resMsgKYC.msgLevelOverview & risk & "')", True)
                    End If
                End If

            End If

            Session("strReason") = sumString
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Function chkCardIdDuplicate(ByVal strUniqueID As String) As Boolean
        Try
            Dim blnDup As Boolean = True

            Dim qryDup = (From tblDup In ds.Tables("dsCustomerCom") Where tblDup.Item("UNIQUEID") = strUniqueID).ToList

            If Not (qryDup.Count = 0) Then
                blnDup = False
            End If

            'If (strUniqueID.Trim = txtUniqueID.Text.Trim) Then
            '    blnDup = False
            'End If

            qryDup = Nothing

            Return blnDup
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Private Function Check_UNIQUEID(ByVal unique_id As String, ByRef ref_custseq As Int32) As Boolean
        Dim unique As Boolean = False
        Dim qry_cust = From cust In KYCEntity.MCUSTOMER
                            Where cust.UNIQUEID = unique_id
                            Select cust.CUSTSEQ, cust.UNIQUEID

        If qry_cust.Count() > 0 Then
            For Each r In qry_cust
                ref_custseq = r.CUSTSEQ
                Exit For
            Next
            unique = True
        End If

        Return unique
    End Function

    Private Sub SaveNew()  'บันทึกข้อมูลใหม่
        clsDatabase = New clsDatabase
        KYCEntity = New KYCEntities
        KYCEntity.Connection.Open()
        Using transaction As System.Data.Common.DbTransaction = KYCEntity.Connection.BeginTransaction()
            Try

                sql = "select " & System.Configuration.ConfigurationSettings.AppSettings("SequentMCUSTOMER_S") & " from dual"
                If (ds.Tables.Contains("GENCUST")) Then
                    ds.Tables("GENCUST").Clear()
                    ds.Tables("GENCUST").ImportRow(clsDatabase.QueryDataSet(sql, "GENCUST").Tables("GENCUST").Rows(0))
                Else
                    ds.Tables.Add(clsDatabase.QueryDataSet(sql, "GENCUST").Tables("GENCUST").Copy)
                End If
                CustSeq = ds.Tables("GENCUST").Rows(0)("NEXTVAL")
                Session("CUSTSEQ") = ds.Tables("GENCUST").Rows(0)("NEXTVAL")

                ''''Prachak ---> save new account to mcustomer
                saveNewCompany(CustSeq)
                saveUpdateAuthority(CustSeq)

                ''''Prachak'''''''''''''''''''' 
                Me.Save_to_MCUST_C_CATE_TYPE(CustSeq)
                Me.Save_to_Cust_Income_source(CustSeq)
                Me.Save_to_Cust_SanctList(CustSeq)
                Me.Save_to_Cust_Politician(CustSeq)
                Me.Save_to_Cust_Reason(CustSeq)
                Me.Save_to_Cust_BO(CustSeq)
                Me.Save_BO_ID_To_Mcustomer()
                Me.Save_to_Cust_Product(CustSeq)
                Me.Save_to_Cust_AddedService(CustSeq)

                ''''''''''''''''''''''''''''''''''''''''
                KYCEntity.SaveChanges()
                transaction.Commit()
            Catch ex As Exception
                transaction.Rollback()
                KYCEntity = Nothing
                Throw ex
            End Try

        End Using

        KYCEntity = Nothing
        clsDatabase = Nothing

    End Sub

    Private Function statusTran(ByVal keyRef As Integer) As Integer 'ตรวจสอบว่าตาราง KYC มีข้อมูลของลูกค้าคนนี้หรือยัง
        Dim KYC As Integer = CInt(Session("KYC"))
        If KYC = 1 Then
            KYC = 2
        ElseIf KYC = 2 Then
            KYC = 4
        ElseIf KYC = 3 Then
            KYC = 6
        End If

        Dim NewCustSEQ As Integer
        If keyRef = 0 Then
            NewCustSEQ = CustSeq
        Else
            NewCustSEQ = keyRef
        End If

        Dim tran As Integer
        Dim qryK = (From k In KYCEntity.RKYC
                     Where k.CUSTSEQ = NewCustSEQ And k.ANSWERTYPE = KYC
                     Select k.CUSTSEQ).ToList

        Dim i As Integer = qryK.Count
        If i = 0 Then
            tran = 0 'New
        Else
            tran = 1 'Edit
        End If
        Return tran
    End Function

    Private Sub saveNewCompany(ByVal CustSeqCom As Integer)
        Dim clsMoney As New clsMoney
        Dim newCustomer As New MCUSTOMER

        newCustomer.TRANTYPE = ddlTranType.SelectedValue
        newCustomer.CUSTSEQ = CustSeqCom
        newCustomer.CUSTTYPE = 2
        newCustomer.CUSTSUBTYPE = ddlBizType.SelectedValue
        newCustomer.AMLCDDOVERVIEW = lblLevelCom.Text.Trim
        ' newCustomer.AMLCDDBEFORE = lblLevelCom.Text.Trim
        newCustomer.AMLREASONOVERVIEW = txtReason.Text.Trim

        newCustomer.UNIQUEID = txtBizNo.Text.Trim
        'newCustomer.THPREFIX = ddlPrefix.SelectedValue
        newCustomer.THFIRSTNAME = txtNameTH.Text.Trim
        newCustomer.ENFIRSTNAME = txtNameEN.Text.ToUpper.Trim
        newCustomer.NATIONALITY = ddlNationality.SelectedValue

        newCustomer.SALARYPERMONTH = clsMoney.deleteComma(txtSalaryPerMonth.Text.Trim)
        newCustomer.ISANSWERSALARY = Convert.ToInt32(rdoAnsSalary.SelectedValue)

        ''''Prachak ''''''''''''''''''''''''''''''''''''''''''''''
        newCustomer.PERIOD_MONTH = CInt(Me.lblPERIOD_MONTH.Text)
        If lblNEXT_REVIEW.Text <> "" Then
            newCustomer.NEXT_REVIEW = Me.lblNEXT_REVIEW.Text
        End If

        If Not ddlBusiness1.SelectedIndex = 0 Then
            newCustomer.BIZTYPE1 = ddlBusiness1.SelectedValue
            newCustomer.BIZTYPEOTHER1 = txtBizOther1.Text.Trim
        Else
            newCustomer.BIZTYPE1 = Nothing
            newCustomer.BIZTYPEOTHER1 = ""
        End If
        If Not ddlBusiness2.SelectedIndex = 0 Then
            newCustomer.BIZTYPE2 = ddlBusiness2.SelectedValue
            newCustomer.BIZTYPEOTHER2 = txtBizOther2.Text.Trim
        Else
            newCustomer.BIZTYPE2 = Nothing
            newCustomer.BIZTYPEOTHER2 = ""
        End If
        If Not ddlBusiness3.SelectedIndex = 0 Then
            newCustomer.BIZTYPE3 = ddlBusiness3.SelectedValue
            newCustomer.BIZTYPEOTHER3 = txtBizOther3.Text.Trim
        Else
            newCustomer.BIZTYPE3 = Nothing
            newCustomer.BIZTYPEOTHER3 = ""
        End If

        newCustomer.BIZDESC1 = txtDes1.Text.Trim
        newCustomer.BIZDESC2 = txtDes2.Text.Trim
        newCustomer.BIZDESC3 = txtDes3.Text.Trim

        newCustomer.INCOMESOURCE1 = ddlIncomeSource1.SelectedValue
        If Not ddlIncomeSource2.SelectedIndex = 0 Then
            newCustomer.INCOMESOURCE2 = ddlIncomeSource2.SelectedValue
        End If
        If Not ddlIncomeSource3.SelectedIndex = 0 Then
            newCustomer.INCOMESOURCE3 = ddlIncomeSource3.SelectedValue
        End If

        If Not chkNGO.SelectedIndex = -1 Then
            newCustomer.NGOCHECK1 = chkNGO.SelectedValue
        End If
        If Not chkRegister.SelectedIndex = -1 Then
            newCustomer.COMPCHECK1 = chkRegister.SelectedValue
        End If
        newCustomer.AMLCDDBEFORE = lblOverview.Text.Trim
        newCustomer.AMLCDD = lblOverview.Text.Trim
        newCustomer.AMLREASON = txtReasonOverview.Text.Trim

        If Session("KYC") = 1 Then
            newCustomer.DEPUPDATE = "D"
            newCustomer.DEPD = "N"
            newCustomer.DEPL = "-"
            newCustomer.DEPP = "-"
            newCustomer.DEPN = "-"
        ElseIf Session("KYC") = 2 Then
            newCustomer.DEPUPDATE = "L"
            newCustomer.DEPL = "N"
            newCustomer.DEPD = "-"
            newCustomer.DEPP = "-"
            newCustomer.DEPN = "-"
        ElseIf Session("KYC") = 3 Then
            newCustomer.DEPUPDATE = "P"
            newCustomer.DEPP = "N"
            newCustomer.DEPD = "-"
            newCustomer.DEPL = "-"
            newCustomer.DEPN = "-"
        ElseIf Session("KYC") = 5 Then
            newCustomer.DEPUPDATE = "N"
            newCustomer.DEPP = "-"
            newCustomer.DEPD = "-"
            newCustomer.DEPL = "-"
            newCustomer.DEPN = "N"

        End If
        newCustomer.UPDATEBY = clsSessionMenuRight.getUserName
        If PanelApprove.Enabled = True Then
            newCustomer.APPROVECODE = ddlApprove.SelectedValue
            newCustomer.APPROVEREASON = txtReasonApp.Text
            newCustomer.LASTAPPROVECODE = ddlApprove.SelectedValue
            If txtDApproveDate.Text = "" Then
                newCustomer.LASTAPPROVEDATE = Now
            Else
                convertDate = New clsDateFormat
                newCustomer.LASTAPPROVEDATE = convertDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, txtDApproveDate.Text)
            End If
            newCustomer.LASTAPPROVENAME = txtApproveNo.Text
            newCustomer.LASTAPPROVENO = txtApproveNo.Text
            newCustomer.LASTAPPROVELEVEL = lblLevelCom.Text
            newCustomer.LASTKYCUPDATEBY = clsSessionMenuRight.getUserName
            newCustomer.LASTKYCUPDATEDATE = Now
        Else
            newCustomer.APPROVECODE = 0
            newCustomer.APPROVEREASON = ""
            newCustomer.LASTKYCUPDATEBY = clsSessionMenuRight.getUserName
            newCustomer.LASTKYCUPDATEDATE = Now
        End If

        newCustomer.BRANCHCODE = clsSessionMenuRight.getBranchCode
        newCustomer.ZONECODE = clsSessionMenuRight.getZoneCode
        newCustomer.DEPTCODE = clsSessionMenuRight.getDeptCode
        newCustomer.ALLCODERIGHT = clsSessionMenuRight.getAllCodeRight

        newCustomer.CREATEBY = clsSessionMenuRight.getUserName
        newCustomer.CREATEDATE = Now.ToShortDateString

        newCustomer.UPDATEDATE = Now.ToShortDateString
        If Not ddlTranType.SelectedValue = 2 Then
            newCustomer.ETL_STATUS = "W"
        Else
            newCustomer.ETL_STATUS = "N"
        End If

        newCustomer.FILTER_RESULT = Me.lblFILTER_RESULT_CUST.Text
        newCustomer.RISK_LEVEL = Me.lblRISK_LEVEL_CUST.Text



        ''''Prachak '''''''''''''''''''''''
        newCustomer.CIF_CBS_NO = Me.lblCIF_CBS_NO.Text
        newCustomer.CIF_NPA_NO = Me.txtCIF_NPA_NO.Text
        newCustomer.CIF_FDR_NO = Me.txtCIF_FDR_NO.Text

        ''''Prachak '''''''''''''''''''''''''
        newCustomer.FORMALADDR = Me.txtFORMALADDR.Text
        newCustomer.FORMALMOO = Me.txtFormalMoo.Text
        newCustomer.FORMALSTREET = Me.txtFormalStreetDesc.Text
        newCustomer.FORMALSOIDESC = Me.txtFormalSoiDESC.Text
        newCustomer.FORMALSTREETDESC = Me.txtFormalStreetDesc.Text
        newCustomer.FORMALBUILDING = Me.txtFormalBuilding.Text
        newCustomer.FORMALPROVINCE = ddlFormalProvince.SelectedValue
        newCustomer.FORMALAMPHOR = ddlFormalAmphor.SelectedValue
        newCustomer.FORMALTAMBOL = ddlFormalTambol.SelectedValue
        newCustomer.FORMALZIP = Me.txtFORMALZIP.Text
        newCustomer.FORMALPHONE1 = Me.txtFormalPhone1.Text
        newCustomer.FORMALPHONE2 = Me.txtFormalPhone2.Text
        newCustomer.FORMALPHONE3 = Me.txtFormalPhone3.Text
        newCustomer.FORMALFAX = Me.txtFormalFax1_1.Text

        ''''Prachak '''''''''''''''''''''''''
        newCustomer.WORKADDR = Me.txtWORKADDR.Text
        newCustomer.WORKMOO = Me.txtWORKMOO.Text
        newCustomer.WORKSTREET = Me.txtWORKSTREETDESC.Text
        newCustomer.WORKSOIDESC = Me.txtWORKSOIDESC.Text
        newCustomer.WORKSTREETDESC = Me.txtWORKSTREETDESC.Text
        newCustomer.WORKLOCALITY = Me.txtWORKLOCALITY.Text
        newCustomer.WORKPROVINCE = ddlWORKPROVINCE.SelectedValue
        newCustomer.WORKAMPHOR = ddlWORKAMPHOR.SelectedValue
        newCustomer.WORKTAMBOL = ddlWORKTAMBOL.SelectedValue
        newCustomer.WORKZIP = Me.txtWORKZIP.Text
        newCustomer.WORKPHONE1 = Me.txtWORKPHONE1.Text
        newCustomer.WORKPHONE2 = Me.txtWORKPHONE1.Text
        newCustomer.WORKPHONE3 = Me.txtWORKPHONE1.Text
        newCustomer.WORKFAX = Me.txtWORKFAX.Text


        ''''Prachak '''''''''''''''''''''''''
        newCustomer.TAX_ID = Me.txtTAX_ID.Text
        newCustomer.BIRTH_DATE_TH = Me.lbBIRTH_DATE_TH.Text
        newCustomer.BIRTH_DATE_EN = Me.lbBIRTH_DATE_EN.Text
        If Not DdOtherID.SelectedValue = -1 Then
            newCustomer.TYPEEVIDENCE = Me.DdOtherID.SelectedValue
            newCustomer.TYPEEVIDENCE_NO = Me.txtTYPEEVIDENCE_NO.Text
        End If

        ''''Prachak '''''''''''''''''''''''''
        newCustomer.F_POLITIC = Me.lblF_POLITIC.Text
        newCustomer.OTH_NAT_ADD_1 = Me.txtOTH_NAT_ADD_1.Text
        newCustomer.OTH_NAT_ADD_2 = Me.txtOTH_NAT_ADD_2.Text
        newCustomer.OTH_NAT_ZIP = Me.txtOTH_NAT_ZIP.Text
        newCustomer.OTH_NAT_STREET = Me.txtOTH_NAT_STREET.Text
        newCustomer.OTH_NAT_PHN = Me.txtOTH_NAT_PHN.Text
        newCustomer.OTH_NAT_PHN_EXT = Me.txtOTH_NAT_PHN_EXT.Text
        newCustomer.OTH_NAT_MOBILE = Me.txtOTH_NAT_MOBILE.Text
        newCustomer.OTH_NAT_FAX = Me.txtOTH_NAT_FAX.Text
        newCustomer.OTH_NAT_EMAIL = Me.txtOTH_NAT_EMAIL.Text
        newCustomer.AVR_REVENUE = Me.ddlAVR_REVENUE.SelectedValue
        newCustomer.AVR_EXPENSE = Me.ddlAVR_EXPENSE.SelectedValue
        newCustomer.PRODUCT_NAME = Me.ddlPRODUCT_NAME.SelectedValue
        newCustomer.ADDITIONAL_SERVICE = Me.ddlADDED_SERVICE.SelectedValue

        ''''''''''''''''''''''''''''''''''''''
        KYCEntity.AddToMCUSTOMER(newCustomer)

    End Sub

    Private Sub saveUpdate()

        clsDatabase = New clsDatabase
        KYCEntity = New KYCEntities
        KYCEntity.Connection.Open()
        Using transaction As System.Data.Common.DbTransaction = KYCEntity.Connection.BeginTransaction()
            Try

                saveUpdateCompany()
                saveUpdateAuthority(CustSeq)

                ''''Prachak'''''''''''''''''''' 
                Me.Save_to_MCUST_C_CATE_TYPE(CustSeq)
                Me.Save_to_Cust_Income_source(CustSeq)
                Me.Save_to_Cust_SanctList(CustSeq)
                Me.Save_to_Cust_Politician(CustSeq)
                Me.Save_to_Cust_Reason(CustSeq)
                Me.Save_to_Cust_BO(CustSeq)
                Me.Save_BO_ID_To_Mcustomer()
                Me.Save_to_Cust_Product(CustSeq)
                Me.Save_to_Cust_AddedService(CustSeq)
                ''''''''''''''''''''''''''''''''''''''''
                KYCEntity.SaveChanges()
                transaction.Commit()
            Catch ex As Exception
                transaction.Rollback()
                ScriptManager.RegisterStartupScript(btnNext, Page.GetType(), "alert", "alert('Error : " & ex.ToString & " Error message : " & ex.Message & "')", True)

            End Try
        End Using
        KYCEntity = Nothing
        clsDatabase = Nothing
    End Sub

    Private Sub saveUpdateCompany()
        Dim clsMoney As New clsMoney
        Try

            Dim updateCust = (From Cust In KYCEntity.MCUSTOMER
                             Where Cust.CUSTSEQ = CustSeq
                             Select Cust).First()


            ''''Prachak '''''''''''''''''''''''
            updateCust.CIF_CBS_NO = Me.lblCIF_CBS_NO.Text
            updateCust.CIF_NPA_NO = Me.txtCIF_NPA_NO.Text
            updateCust.CIF_FDR_NO = Me.txtCIF_FDR_NO.Text


            ''''Prachak ''''''''''''''''''''''''''''''''''''''''''''''
            updateCust.PERIOD_MONTH = CInt(Me.lblPERIOD_MONTH.Text)
            If lblNEXT_REVIEW.Text <> "" Then
                updateCust.NEXT_REVIEW = Me.lblNEXT_REVIEW.Text
            End If

            ''''Prachak ''''''''''''''''''''''''''''''''''' 
            updateCust.FILTER_RESULT = Me.lblFILTER_RESULT_CUST.Text
            updateCust.RISK_LEVEL = Me.lblRISK_LEVEL_CUST.Text

            updateCust.BIRTH_DATE_TH = Me.lbBIRTH_DATE_TH.Text
            updateCust.BIRTH_DATE_EN = Me.lbBIRTH_DATE_EN.Text

            updateCust.TAX_ID = Me.txtTAX_ID.Text
            updateCust.BIRTH_DATE_TH = Me.lbBIRTH_DATE_TH.Text
            updateCust.BIRTH_DATE_EN = Me.lbBIRTH_DATE_EN.Text

            If Not DdOtherID.SelectedValue = -1 Then
                updateCust.TYPEEVIDENCE = Me.DdOtherID.SelectedValue
            End If
            updateCust.TYPEEVIDENCE_NO = Me.txtTYPEEVIDENCE_NO.Text
            ''''Prachak ''''''''''''''''''''''''''''''''''' 
            updateCust.FORMALADDR = Me.txtFORMALADDR.Text
            updateCust.FORMALMOO = Me.txtFormalMoo.Text
            updateCust.FORMALSTREET = Me.txtFormalStreetDesc.Text
            updateCust.FORMALSOIDESC = Me.txtFormalSoiDESC.Text
            updateCust.FORMALSTREETDESC = Me.txtFormalStreetDesc.Text
            updateCust.FORMALBUILDING = Me.txtFormalBuilding.Text
            updateCust.FORMALPROVINCE = ddlFormalProvince.SelectedValue
            updateCust.FORMALAMPHOR = ddlFormalAmphor.SelectedValue
            updateCust.FORMALTAMBOL = ddlFormalTambol.SelectedValue
            updateCust.FORMALZIP = Me.txtFORMALZIP.Text
            updateCust.FORMALPHONE1 = Me.txtFormalPhone1.Text
            updateCust.FORMALPHONE2 = Me.txtFormalPhone2.Text
            updateCust.FORMALPHONE3 = Me.txtFormalPhone3.Text
            updateCust.FORMALFAX = Me.txtFormalFax1_1.Text

            ''''Prachak ''''''''''''''''''''''''''''''''''' 
            updateCust.WORKADDR = Me.txtWORKADDR.Text
            updateCust.WORKMOO = Me.txtWORKMOO.Text
            updateCust.WORKSTREET = Me.txtWORKSTREETDESC.Text
            updateCust.WORKSOIDESC = Me.txtWORKSOIDESC.Text
            updateCust.WORKSTREETDESC = Me.txtWORKSTREETDESC.Text
            updateCust.WORKLOCALITY = Me.txtWORKLOCALITY.Text
            updateCust.WORKPROVINCE = ddlWORKPROVINCE.SelectedValue
            updateCust.WORKAMPHOR = ddlWORKAMPHOR.SelectedValue
            updateCust.WORKTAMBOL = ddlWORKTAMBOL.SelectedValue
            updateCust.WORKZIP = Me.txtWORKZIP.Text
            updateCust.WORKPHONE1 = Me.txtWORKPHONE1.Text
            updateCust.WORKPHONE2 = Me.txtWORKPHONE2.Text
            updateCust.WORKPHONE3 = Me.txtWORKPHONE3.Text
            updateCust.WORKFAX = Me.txtWORKFAX.Text

            ''''Prachak ''''''''''''''''''''''''''''''''''' 


            updateCust.F_POLITIC = Me.lblF_POLITIC.Text
            updateCust.OTH_NAT_ADD_1 = Me.txtOTH_NAT_ADD_1.Text
            updateCust.OTH_NAT_ADD_2 = Me.txtOTH_NAT_ADD_2.Text
            updateCust.OTH_NAT_ZIP = Me.txtOTH_NAT_ZIP.Text
            updateCust.OTH_NAT_STREET = Me.txtOTH_NAT_STREET.Text
            updateCust.OTH_NAT_PHN = Me.txtOTH_NAT_PHN.Text
            updateCust.OTH_NAT_PHN_EXT = Me.txtOTH_NAT_PHN_EXT.Text
            updateCust.OTH_NAT_MOBILE = Me.txtOTH_NAT_MOBILE.Text
            updateCust.OTH_NAT_FAX = Me.txtOTH_NAT_FAX.Text
            updateCust.OTH_NAT_EMAIL = Me.txtOTH_NAT_EMAIL.Text
            updateCust.AVR_REVENUE = Me.ddlAVR_REVENUE.SelectedValue
            updateCust.AVR_EXPENSE = Me.ddlAVR_EXPENSE.SelectedValue
            updateCust.PRODUCT_NAME = Me.ddlPRODUCT_NAME.SelectedValue
            updateCust.ADDITIONAL_SERVICE = Me.ddlADDED_SERVICE.SelectedValue

            updateCust.TRANTYPE = ddlTranType.SelectedValue
            updateCust.AMLCDDOVERVIEW = lblLevelCom.Text.Trim

            updateCust.AMLREASONOVERVIEW = txtReason.Text.Trim
            updateCust.UNIQUEID = txtBizNo.Text.Trim
            updateCust.CUSTSUBTYPE = ddlBizType.SelectedValue
            ' updateCust.THPREFIX = ddlPrefix.SelectedValue
            updateCust.THFIRSTNAME = txtNameTH.Text.Trim

            updateCust.ENFIRSTNAME = txtNameEN.Text.ToUpper.Trim
            updateCust.NATIONALITY = ddlNationality.SelectedValue
            updateCust.SALARYPERMONTH = clsMoney.deleteComma(txtSalaryPerMonth.Text.Trim)
            updateCust.ISANSWERSALARY = Convert.ToInt32(rdoAnsSalary.SelectedValue)



            If Not ddlBusiness1.SelectedIndex = 0 Then
                updateCust.BIZTYPE1 = ddlBusiness1.SelectedValue
                updateCust.BIZTYPEOTHER1 = txtBizOther1.Text.Trim
            Else
                updateCust.BIZTYPE1 = Nothing
                updateCust.BIZTYPEOTHER1 = ""
            End If
            If Not ddlBusiness2.SelectedIndex = 0 Then
                updateCust.BIZTYPE2 = ddlBusiness2.SelectedValue
                updateCust.BIZTYPEOTHER2 = txtBizOther2.Text.Trim
            Else
                updateCust.BIZTYPE2 = Nothing
                updateCust.BIZTYPEOTHER2 = ""
            End If
            If Not ddlBusiness3.SelectedIndex = 0 Then
                updateCust.BIZTYPE3 = ddlBusiness3.SelectedValue
                updateCust.BIZTYPEOTHER3 = txtBizOther3.Text.Trim
            Else
                updateCust.BIZTYPE3 = Nothing
                updateCust.BIZTYPEOTHER3 = ""
            End If

            updateCust.BIZDESC1 = txtDes1.Text.Trim
            updateCust.BIZDESC2 = txtDes2.Text.Trim
            updateCust.BIZDESC3 = txtDes3.Text.Trim

            updateCust.INCOMESOURCE1 = ddlIncomeSource1.SelectedValue
            If ddlIncomeSource2.SelectedIndex = 0 Then
                updateCust.INCOMESOURCE2 = Nothing
            Else
                updateCust.INCOMESOURCE2 = ddlIncomeSource2.SelectedValue
            End If
            If ddlIncomeSource3.SelectedIndex = 0 Then
                updateCust.INCOMESOURCE3 = Nothing
            Else
                updateCust.INCOMESOURCE3 = ddlIncomeSource3.SelectedValue
            End If

            If Not chkNGO.SelectedIndex = -1 Then
                updateCust.NGOCHECK1 = chkNGO.SelectedValue
            End If
            If Not chkRegister.SelectedIndex = -1 Then
                updateCust.COMPCHECK1 = chkRegister.SelectedValue
            End If

            updateCust.AMLCDD = lblOverview.Text.Trim
            updateCust.AMLREASON = txtReasonOverview.Text

            If Not (lblLevelComOld.Text.Trim = "0" Or lblLevelComOld.Text.Trim = "") Then
                updateCust.AMLCDDBEFORE = CInt(lblLevelComOld.Text.Trim)
            Else
                updateCust.AMLCDDBEFORE = lblOverview.Text.Trim
            End If



            If Session("KYC") = 1 Then
                updateCust.DEPUPDATE = "D"
                updateCust.DEPD = "N"
            ElseIf Session("KYC") = 2 Then
                updateCust.DEPUPDATE = "L"
                updateCust.DEPL = "N"
            ElseIf Session("KYC") = 3 Then
                updateCust.DEPUPDATE = "P"
                updateCust.DEPP = "N"
            ElseIf Session("KYC") = 5 Then
                updateCust.DEPUPDATE = "N"
                updateCust.DEPN = "N"
            End If
            updateCust.UPDATEBY = clsSessionMenuRight.getUserName
            If PanelApprove.Enabled = True Then
                updateCust.APPROVECODE = ddlApprove.SelectedValue
                updateCust.APPROVEREASON = txtReasonApp.Text
                updateCust.LASTAPPROVECODE = ddlApprove.SelectedValue
                If txtDApproveDate.Text = "" Then
                    updateCust.LASTAPPROVEDATE = Now
                Else
                    convertDate = New clsDateFormat
                    updateCust.LASTAPPROVEDATE = convertDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, txtDApproveDate.Text)
                End If
                updateCust.LASTAPPROVENAME = txtApproveNo.Text
                updateCust.LASTAPPROVENO = txtApproveNo.Text
                updateCust.LASTAPPROVELEVEL = lblLevelCom.Text
                updateCust.LASTKYCUPDATEBY = clsSessionMenuRight.getUserName
                updateCust.LASTKYCUPDATEDATE = Now
            Else
                updateCust.APPROVECODE = 0
                updateCust.APPROVEREASON = ""
                updateCust.LASTKYCUPDATEBY = clsSessionMenuRight.getUserName
                updateCust.LASTKYCUPDATEDATE = Now
            End If

            updateCust.BRANCHCODE = clsSessionMenuRight.getBranchCode
            updateCust.ZONECODE = clsSessionMenuRight.getZoneCode
            updateCust.DEPTCODE = clsSessionMenuRight.getDeptCode
            updateCust.ALLCODERIGHT = clsSessionMenuRight.getAllCodeRight

            updateCust.UPDATEDATE = Now.ToShortDateString
            If Not ddlTranType.SelectedValue = 2 Then
                updateCust.ETL_STATUS = "W"
            Else
                updateCust.ETL_STATUS = "N"
            End If

            updateCust.AMLCDDBEFORE = lblLevelComOld.Text.Trim


            KYCEntity.SaveChanges()
            updateCust = Nothing
        Catch ex As Exception

        End Try

    End Sub

    Private Sub saveUpdateAuthority(ByVal CustSeqCom As Integer)

        Dim deleteCust = (From Cust In KYCEntity.MCOMPRELATION
                       Where Cust.CUSTSEQ = CustSeqCom
                       Select Cust).ToList
        If Not deleteCust.Count = 0 Then
            For i As Integer = 0 To deleteCust.Count - 1
                KYCEntity.DeleteObject(deleteCust(i))
            Next
            KYCEntity.SaveChanges()
        End If
        deleteCust = Nothing

        Dim refCust As Integer = 0
        Dim custtype As Integer = 0


        For i As Integer = 0 To ds.Tables("dsCustomerCom").Rows.Count - 1

            If ds.Tables("dsCustomerCom").Rows(i)("CreateBy") Is DBNull.Value Then
                refCust = updateAuthority(i)
            ElseIf ds.Tables("dsCustomerCom").Rows(i)("CreateBy") = "AutoGenPK" Then
                refCust = newAuthority(i)
            Else
                refCust = updateAuthority(i)
            End If

            If refCust <> 0 Then
                Dim newRef As New MCOMPRELATION
                newRef.CUSTSEQ = CustSeqCom
                newRef.REFSEQ = i + 1
                newRef.REFCUSTSEQ = refCust
                newRef.POCODE = CInt(ds.Tables("dsCustomerCom").Rows(i)("POCODE"))
                KYCEntity.AddToMCOMPRELATION(newRef)
            End If
        Next
        'If statusTran(refCust) = 0 Then 'New
        '    If Not (Session("KYC") = "2" Or Session("KYC") = "5") Then

        '        Dim sql As String = "select " & System.Configuration.ConfigurationSettings.AppSettings("SequentRKYC_S") & " from dual"


        '        If (ds.Tables.Contains("GENKYC")) Then
        '            ds.Tables("GENKYC").Clear()
        '            ds.Tables("GENKYC").ImportRow(clsDatabase.QueryDataSet(sql, "GENKYC").Tables("GENKYC").Rows(0))
        '        Else
        '            ds.Tables.Add(clsDatabase.QueryDataSet(sql, "GENKYC").Tables("GENKYC").Copy)
        '        End If
        '        Dim KYCSeq As Integer = ds.Tables("GENKYC").Rows(0)("NEXTVAL")

        '        saveKYC(KYCSeq, refCust, custtype)

        '    End If

        'Else 'Edit
        '    saveUpdateKYC(refCust, custtype)
        'End If
        'If (ds.Tables.Contains("GENKYC")) Then
        '    ds.Tables.Remove("GENKYC")
        'End If

    End Sub

    Private Function newAuthority(ByVal i As Integer) As Integer
        Dim newCustomer As New MCUSTOMER
        Dim ref_custseq As Int32
        ' ----- เช็ค เลขบัตรประชาชน ถ้าซ้ำจะต้องไม่เพิ่ม MCUSTOMER
        If Check_UNIQUEID(ds.Tables("dsCustomerCom").Rows(i)("UNIQUEID").ToString(), ref_custseq) Then
            Return ref_custseq
        End If

        sql = "select " & System.Configuration.ConfigurationSettings.AppSettings("SequentMCUSTOMER_S") & " from dual"
        If (ds.Tables.Contains("GENCUST")) Then
            ds.Tables("GENCUST").Clear()
            ds.Tables("GENCUST").ImportRow(clsDatabase.QueryDataSet(sql, "GENCUST").Tables("GENCUST").Rows(0))
        Else
            ds.Tables.Add(clsDatabase.QueryDataSet(sql, "GENCUST").Tables("GENCUST").Copy)
        End If
        Dim custSeqA As Integer = ds.Tables("GENCUST").Rows(0)("NEXTVAL")

        newCustomer.TRANTYPE = 4 'ผู้ถือหุ้น
        newCustomer.CUSTSEQ = custSeqA
        newCustomer.CUSTTYPE = CInt(ds.Tables("dsCustomerCom").Rows(i)("CUSTTYPE"))
        newCustomer.CUSTSUBTYPE = CInt(ds.Tables("dsCustomerCom").Rows(i)("CUSTSUBTYPE"))
        newCustomer.AMLCDD = CInt(ds.Tables("dsCustomerCom").Rows(i)("AMLCDD"))
        newCustomer.AMLREASON = ds.Tables("dsCustomerCom").Rows(i)("AMLREASON").ToString
        newCustomer.UNIQUEID = ds.Tables("dsCustomerCom").Rows(i)("UNIQUEID")
        newCustomer.THPREFIX = CInt(ds.Tables("dsCustomerCom").Rows(i)("THPREFIX"))

        newCustomer.THFIRSTNAME = CStr(ds.Tables("dsCustomerCom").Rows(i)("THFIRSTNAME")).ToString
        newCustomer.ENFIRSTNAME = CStr(ds.Tables("dsCustomerCom").Rows(i)("ENFIRSTNAME"))

        'newCustomer.THFIRSTNAME = cutSpecialCharacter(CStr(ds.Tables("dsCustomerCom").Rows(i)("THFIRSTNAME")).ToString)
        'newCustomer.ENFIRSTNAME = cutSpecialCharacter(CStr(ds.Tables("dsCustomerCom").Rows(i)("ENFIRSTNAME")).ToString)
        If Not ds.Tables("dsCustomerCom").Rows(i)("NATIONALITY") Is DBNull.Value Then
            newCustomer.NATIONALITY = CInt(ds.Tables("dsCustomerCom").Rows(i)("NATIONALITY"))
        End If
        If Not ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE1") Is DBNull.Value Then
            newCustomer.BIZTYPE1 = CInt(ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE1"))
        End If
        newCustomer.BIZTYPEOTHER1 = ds.Tables("dsCustomerCom").Rows(i)("BIZTYPEOTHER1").ToString
        If Not ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE2") Is DBNull.Value Then
            newCustomer.BIZTYPE2 = CInt(ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE2"))
        End If
        newCustomer.BIZTYPEOTHER2 = ds.Tables("dsCustomerCom").Rows(i)("BIZTYPEOTHER2").ToString
        If Not ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE3") Is DBNull.Value Then
            newCustomer.BIZTYPE3 = CInt(ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE3"))
        End If
        newCustomer.BIZTYPEOTHER3 = ds.Tables("dsCustomerCom").Rows(i)("BIZTYPEOTHER3").ToString
        newCustomer.BIZDESC1 = ds.Tables("dsCustomerCom").Rows(i)("BIZDESC1").ToString
        newCustomer.BIZDESC2 = ds.Tables("dsCustomerCom").Rows(i)("BIZDESC2").ToString
        newCustomer.BIZDESC3 = ds.Tables("dsCustomerCom").Rows(i)("BIZDESC3").ToString

        newCustomer.BRANCHCODE = clsSessionMenuRight.getBranchCode
        newCustomer.ZONECODE = clsSessionMenuRight.getZoneCode
        newCustomer.DEPTCODE = clsSessionMenuRight.getDeptCode
        newCustomer.ALLCODERIGHT = clsSessionMenuRight.getAllCodeRight

        newCustomer.CREATEBY = clsSessionMenuRight.getUserName
        newCustomer.CREATEDATE = Now.ToShortDateString
        newCustomer.UPDATEBY = clsSessionMenuRight.getUserName
        newCustomer.UPDATEDATE = Now.ToShortDateString

        If CInt(ds.Tables("dsCustomerCom").Rows(i)("CUSTTYPE")) = 1 Then
            'newCustomer.CUSTIDTYPE = CInt(ds.Tables("dsCustomerCom").Rows(i)("CUSTIDTYPE"))
            newCustomer.THMIDNAME = ds.Tables("dsCustomerCom").Rows(i)("THMIDNAME").ToString
            newCustomer.THLASTNAME = ds.Tables("dsCustomerCom").Rows(i)("THLASTNAME").ToString
            'newCustomer.ENPREFIX = CInt(ds.Tables("dsCustomerCom").Rows(i)("ENPREFIX"))
            newCustomer.ENMIDNAME = ds.Tables("dsCustomerCom").Rows(i)("ENMIDNAME").ToString
            newCustomer.ENLASTNAME = ds.Tables("dsCustomerCom").Rows(i)("ENLASTNAME").ToString
            'newCustomer.OCCUPATIONTYPE1 = CInt(ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE1"))
            newCustomer.OCCUPATIONTYPEOTHER1 = ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPEOTHER1").ToString
            If Not ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE2") Is DBNull.Value Then
                newCustomer.OCCUPATIONTYPE2 = CInt(ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE2"))
            End If
            newCustomer.OCCUPATIONTYPEOTHER2 = ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPEOTHER2").ToString
            If Not ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE3") Is DBNull.Value Then
                newCustomer.OCCUPATIONTYPE3 = CInt(ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE3"))
            End If
            newCustomer.OCCUPATIONTYPEOTHER3 = ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPEOTHER3").ToString
        Else
            'newCustomer.AMLCDDOVERVIEW = CInt(ds.Tables("dsCustomerCom").Rows(i)("AMLCDDOVERVIEW"))
            newCustomer.AMLREASONOVERVIEW = ds.Tables("dsCustomerCom").Rows(i)("AMLREASONOVERVIEW").ToString
        End If
        If PanelApprove.Enabled = True Then
            newCustomer.APPROVECODE = ddlApprove.SelectedValue
            newCustomer.APPROVEREASON = txtReasonApp.Text
            newCustomer.LASTAPPROVECODE = ddlApprove.SelectedValue
            If txtDApproveDate.Text = "" Then
                newCustomer.LASTAPPROVEDATE = Now
            Else
                convertDate = New clsDateFormat
                newCustomer.LASTAPPROVEDATE = convertDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, txtDApproveDate.Text)
            End If
            newCustomer.LASTAPPROVENAME = txtApproveNo.Text
            newCustomer.LASTAPPROVENO = txtApproveNo.Text
            newCustomer.LASTAPPROVELEVEL = CInt(ds.Tables("dsCustomerCom").Rows(i)("AMLCDD"))
            newCustomer.LASTKYCUPDATEBY = clsSessionMenuRight.getUserName
            newCustomer.LASTKYCUPDATEDATE = Now
        Else
            newCustomer.APPROVECODE = 0
            newCustomer.APPROVEREASON = ""
            newCustomer.LASTKYCUPDATEBY = clsSessionMenuRight.getUserName
            newCustomer.LASTKYCUPDATEDATE = Now
        End If
        KYCEntity.AddToMCUSTOMER(newCustomer)

        Return custSeqA

    End Function

    Private Function updateAuthority(ByVal i As Integer) As Integer
        Dim idCust As Integer = CInt(ds.Tables("dsCustomerCom").Rows(i)("CUSTSEQ"))
        Dim updateCust = (From Cust In KYCEntity.MCUSTOMER
                    Where Cust.CUSTSEQ = idCust
                    Select Cust).First

        updateCust.AMLCDD = CInt(ds.Tables("dsCustomerCom").Rows(i)("AMLCDD"))
        updateCust.AMLREASON = ds.Tables("dsCustomerCom").Rows(i)("AMLREASON").ToString
        updateCust.UNIQUEID = ds.Tables("dsCustomerCom").Rows(i)("UNIQUEID")
        updateCust.THPREFIX = CInt(ds.Tables("dsCustomerCom").Rows(i)("THPREFIX"))
        'If ds.Tables("dsCustomerCom").Rows(i)("THFIRSTNAME") Is DBNull.Value Then
        '    updateCust.THFIRSTNAME = ""
        'Else
        '  updateCust.THFIRSTNAME = ds.Tables("dsCustomerCom").Rows(i)("THFIRSTNAME").ToString
        ' End If

        ' updateCust.ENFIRSTNAME = CStr(ds.Tables("dsCustomerCom").Rows(i)("ENFIRSTNAME"))

        ''  updateCust.NATIONALITY = CInt(ds.Tables("dsCustomerCom").Rows(i)("NATIONALITY"))
        'If ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE1") Is DBNull.Value Then
        '    updateCust.BIZTYPE1 = Nothing
        'Else
        '    updateCust.BIZTYPE1 = CInt(ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE1"))
        'End If
        'updateCust.BIZTYPEOTHER1 = ds.Tables("dsCustomerCom").Rows(i)("BIZTYPEOTHER1").ToString
        'If ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE2") Is DBNull.Value Then
        '    updateCust.BIZTYPE2 = Nothing
        'Else
        '    updateCust.BIZTYPE2 = CInt(ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE2"))
        'End If
        'updateCust.BIZTYPEOTHER2 = ds.Tables("dsCustomerCom").Rows(i)("BIZTYPEOTHER2").ToString
        'If ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE3") Is DBNull.Value Then
        '    updateCust.BIZTYPE3 = Nothing
        'Else
        '    updateCust.BIZTYPE3 = CInt(ds.Tables("dsCustomerCom").Rows(i)("BIZTYPE3"))
        'End If
        'updateCust.BIZTYPEOTHER3 = ds.Tables("dsCustomerCom").Rows(i)("BIZTYPEOTHER3").ToString

        'updateCust.BIZDESC1 = ds.Tables("dsCustomerCom").Rows(i)("BIZDESC1").ToString
        'updateCust.BIZDESC2 = ds.Tables("dsCustomerCom").Rows(i)("BIZDESC2").ToString
        'updateCust.BIZDESC3 = ds.Tables("dsCustomerCom").Rows(i)("BIZDESC3").ToString

        'updateCust.INCOMESOURCE1 = CInt(ds.Tables("dsCustomerCom").Rows(i)("INCOMESOURCE1"))
        'If ds.Tables("dsCustomerCom").Rows(i)("INCOMESOURCE2") Is DBNull.Value Then
        '    updateCust.INCOMESOURCE2 = Nothing
        'Else
        '    updateCust.INCOMESOURCE2 = CInt(ds.Tables("dsCustomerCom").Rows(i)("INCOMESOURCE2"))
        'End If
        'If ds.Tables("dsCustomerCom").Rows(i)("INCOMESOURCE3") Is DBNull.Value Then
        '    updateCust.INCOMESOURCE3 = Nothing
        'Else
        '    updateCust.INCOMESOURCE3 = CInt(ds.Tables("dsCustomerCom").Rows(i)("INCOMESOURCE3"))
        'End If


        'If Not ds.Tables("dsCustomerCom").Rows(i)("NGOCHECK1") Is DBNull.Value Then
        '    updateCust.NGOCHECK1 = CInt(ds.Tables("dsCustomerCom").Rows(i)("NGOCHECK1"))
        '    updateCust.COMPCHECK1 = Nothing
        'End If
        'If Not ds.Tables("dsCustomerCom").Rows(i)("COMPCHECK1") Is DBNull.Value Then
        '    updateCust.COMPCHECK1 = CInt(ds.Tables("dsCustomerCom").Rows(i)("COMPCHECK1"))
        '    updateCust.NGOCHECK1 = Nothing
        'End If

        updateCust.BRANCHCODE = clsSessionMenuRight.getBranchCode
        updateCust.ZONECODE = clsSessionMenuRight.getZoneCode
        updateCust.DEPTCODE = clsSessionMenuRight.getDeptCode
        updateCust.ALLCODERIGHT = clsSessionMenuRight.getAllCodeRight

        updateCust.UPDATEBY = clsSessionMenuRight.getUserName
        updateCust.UPDATEDATE = Now.ToShortDateString

        'If CInt(ds.Tables("dsCustomerCom").Rows(i)("CUSTTYPE")) = 1 Then
        '    updateCust.CUSTIDTYPE = CInt(ds.Tables("dsCustomerCom").Rows(i)("CUSTIDTYPE"))
        '    updateCust.THMIDNAME = ds.Tables("dsCustomerCom").Rows(i)("THMIDNAME").ToString
        '    updateCust.THLASTNAME = ds.Tables("dsCustomerCom").Rows(i)("THLASTNAME").ToString
        '    updateCust.ENPREFIX = CInt(ds.Tables("dsCustomerCom").Rows(i)("ENPREFIX"))
        '    updateCust.ENMIDNAME = ds.Tables("dsCustomerCom").Rows(i)("ENMIDNAME").ToString
        '    updateCust.ENLASTNAME = ds.Tables("dsCustomerCom").Rows(i)("ENLASTNAME").ToString
        '    updateCust.OCCUPATIONTYPE1 = CInt(ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE1"))
        '    updateCust.OCCUPATIONTYPEOTHER1 = ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPEOTHER1").ToString
        '    If Not ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE2") Is DBNull.Value Then
        '        updateCust.OCCUPATIONTYPE2 = CInt(ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE2"))
        '    End If
        '    updateCust.OCCUPATIONTYPEOTHER2 = ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPEOTHER2").ToString
        '    If Not ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE3") Is DBNull.Value Then
        '        updateCust.OCCUPATIONTYPE3 = CInt(ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPE3"))
        '    End If
        '    updateCust.OCCUPATIONTYPEOTHER3 = ds.Tables("dsCustomerCom").Rows(i)("OCCUPATIONTYPEOTHER3").ToString
        'Else
        '    updateCust.AMLCDDOVERVIEW = CInt(ds.Tables("dsCustomerCom").Rows(i)("AMLCDDOVERVIEW"))
        '    updateCust.AMLREASONOVERVIEW = ds.Tables("dsCustomerCom").Rows(i)("AMLREASONOVERVIEW").ToString
        'End If
        If PanelApprove.Enabled = True Then
            updateCust.APPROVECODE = ddlApprove.SelectedValue
            updateCust.APPROVEREASON = txtReasonApp.Text
            updateCust.LASTAPPROVECODE = ddlApprove.SelectedValue
            If txtDApproveDate.Text = "" Then
                updateCust.LASTAPPROVEDATE = Now
            Else
                convertDate = New clsDateFormat
                updateCust.LASTAPPROVEDATE = convertDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, txtDApproveDate.Text)
            End If
            updateCust.LASTAPPROVENAME = txtApproveNo.Text
            updateCust.LASTAPPROVENO = txtApproveNo.Text
            updateCust.LASTAPPROVELEVEL = CInt(ds.Tables("dsCustomerCom").Rows(i)("AMLCDD"))
            updateCust.LASTKYCUPDATEBY = clsSessionMenuRight.getUserName
            updateCust.LASTKYCUPDATEDATE = Now
        Else
            updateCust.APPROVECODE = 0
            updateCust.APPROVEREASON = ""
            updateCust.LASTKYCUPDATEBY = clsSessionMenuRight.getUserName
            updateCust.LASTKYCUPDATEDATE = Now
        End If
        KYCEntity.SaveChanges()

        updateCust = Nothing

        Return ds.Tables("dsCustomerCom").Rows(i)("CUSTSEQ")
    End Function

    Private Sub saveKYC(ByVal key As Integer, ByVal keyRef As Integer, ByVal type As Integer) 'บันทึกลงตาราง KYC
        Dim KYC As Integer = CInt(Session("KYC"))
        If type = 1 Then
            If KYC = 1 Then
                KYC = 1
            ElseIf KYC = 2 Then
                KYC = 2
            ElseIf KYC = 3 Then
                KYC = 3
            End If
        Else
            If KYC = 1 Then
                KYC = 2
            ElseIf KYC = 2 Then
                KYC = 4
            ElseIf KYC = 3 Then
                KYC = 6
            End If
        End If


        Dim NewCustSEQ As Integer
        If keyRef = 0 Then
            NewCustSEQ = CustSeq
        Else
            NewCustSEQ = keyRef
        End If

        Dim newKYC As New RKYC
        newKYC.KYCSEQ = key
        newKYC.CUSTSEQ = NewCustSEQ
        newKYC.KYCDATE = Now
        newKYC.ANSWERTYPE = KYC
        newKYC.TRANSTYPE = type
        newKYC.AMLCDD = lblOverview.Text.Trim
        newKYC.AMLREASON = txtReasonOverview.Text.Trim
        newKYC.AMLCDDOVERVIEW = lblLevelCom.Text.Trim
        newKYC.AMLREASONOVERVIEW = txtReason.Text.Trim

        Dim clsFormatDate As clsDateFormat = New clsDateFormat
        'If CInt(lblOverview.Text) > 1 Then
        newKYC.UPDATEBY = clsSessionMenuRight.getUserName
        If PanelApprove.Enabled = True And keyRef = 0 Then

            newKYC.APPROVECODE = ddlApprove.SelectedValue
            newKYC.APPROVENAME = txtApproveNo.Text.Trim
            newKYC.APPROVENO = txtApproveNo.Text.Trim
            newKYC.APPROVEDATE = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, txtDApproveDate.Text)


        Else
            newKYC.APPROVECODE = Nothing
            newKYC.APPROVENAME = Nothing
            newKYC.APPROVENO = Nothing
            newKYC.APPROVEDATE = Nothing
        End If
        clsFormatDate = Nothing

        If Session("KYC") = 1 Then
            newKYC.DEPUPDATE = "D"
        ElseIf Session("KYC") = 2 Then
            newKYC.DEPUPDATE = "L"
        ElseIf Session("KYC") = 3 Then
            newKYC.DEPUPDATE = "P"
        End If
        newKYC.KYCCOMPLETE = "N"
        newKYC.BRANCHCODE = clsSessionMenuRight.getBranchCode
        newKYC.ZONECODE = clsSessionMenuRight.getZoneCode
        newKYC.DEPTCODE = clsSessionMenuRight.getDeptCode
        newKYC.ALLCODERIGHT = clsSessionMenuRight.getAllCodeRight

        newKYC.CREATEBY = clsSessionMenuRight.getUserName
        newKYC.CREATEDATE = Now.ToShortDateString

        newKYC.UPDATEDATE = Now.ToShortDateString

        KYCEntity.AddToRKYC(newKYC)

    End Sub

    Private Sub saveUpdateKYC(ByVal keyRef As Integer, ByVal type As Integer, Optional ByVal seqKYC As Integer = 0)
        Dim KYC As Integer = CInt(Session("KYC"))
        Dim strAccount As String = ""
        If type = 1 Then
            If KYC = 1 Then
                KYC = 1
            ElseIf KYC = 2 Then
                KYC = 2
            ElseIf KYC = 3 Then
                KYC = 3
            End If
        Else
            If KYC = 1 Then
                KYC = 2
            ElseIf KYC = 2 Then
                KYC = 4
            ElseIf KYC = 3 Then
                KYC = 6
            End If
        End If

        Dim NewCustSEQ As Integer
        If keyRef = 0 Then
            NewCustSEQ = CustSeq
        Else
            NewCustSEQ = keyRef
        End If

        ' If rdoAcc.SelectedIndex = 1 Then


        If seqKYC = 0 Then
            strAccount = ddlAcc.SelectedValue
            Dim updateKYC = (From k In KYCEntity.RKYC
                                      Where k.CUSTSEQ = CustSeq And k.ANSWERTYPE = KYC And k.ACCOUNTNO = strAccount
                                      Select k).First

            Dim clsFormatDate As clsDateFormat = New clsDateFormat
            'If CInt(lblOverview.Text) > 1 Then
            updateKYC.UPDATEBY = clsSessionMenuRight.getUserName
            If PanelApprove.Enabled = True And keyRef = 0 Then

                updateKYC.APPROVECODE = ddlApprove.SelectedValue
                updateKYC.APPROVENAME = txtApproveNo.Text.Trim
                updateKYC.APPROVENO = txtApproveNo.Text.Trim
                updateKYC.APPROVEDATE = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, txtDApproveDate.Text)


            Else
                updateKYC.APPROVECODE = Nothing
                updateKYC.APPROVENAME = Nothing
                updateKYC.APPROVENO = Nothing
                updateKYC.APPROVEDATE = Nothing
            End If
            clsFormatDate = Nothing

            updateKYC.AMLCDD = lblOverview.Text.Trim
            updateKYC.AMLREASON = txtReasonOverview.Text.Trim
            updateKYC.AMLCDDOVERVIEW = lblLevelCom.Text.Trim
            updateKYC.AMLREASONOVERVIEW = txtReason.Text.Trim

            If Session("KYC") = 1 Then
                updateKYC.DEPUPDATE = "D"
            ElseIf Session("KYC") = 2 Then
                updateKYC.DEPUPDATE = "L"
            ElseIf Session("KYC") = 3 Then
                updateKYC.DEPUPDATE = "P"
            End If

            updateKYC.BRANCHCODE = clsSessionMenuRight.getBranchCode
            updateKYC.ZONECODE = clsSessionMenuRight.getZoneCode
            updateKYC.DEPTCODE = clsSessionMenuRight.getDeptCode
            updateKYC.ALLCODERIGHT = clsSessionMenuRight.getAllCodeRight


            updateKYC.UPDATEDATE = Now.ToShortDateString
        Else
            ' strAccount = ddlAcc.SelectedValue
            Dim updateKYC = (From k In KYCEntity.RKYC
                                      Where k.CUSTSEQ = CustSeq And k.ANSWERTYPE = KYC And k.KYCSEQ = seqKYC
                                      Select k).First

            Dim clsFormatDate As clsDateFormat = New clsDateFormat
            'If CInt(lblOverview.Text) > 1 Then
            updateKYC.UPDATEBY = clsSessionMenuRight.getUserName
            If PanelApprove.Enabled = True And keyRef = 0 Then

                updateKYC.APPROVECODE = ddlApprove.SelectedValue
                updateKYC.APPROVENAME = txtApproveNo.Text.Trim
                updateKYC.APPROVENO = txtApproveNo.Text.Trim
                updateKYC.APPROVEDATE = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, txtDApproveDate.Text)


            Else
                updateKYC.APPROVECODE = Nothing
                updateKYC.APPROVENAME = Nothing
                updateKYC.APPROVENO = Nothing
                updateKYC.APPROVEDATE = Nothing
            End If
            clsFormatDate = Nothing

            updateKYC.AMLCDD = lblOverview.Text.Trim
            updateKYC.AMLREASON = txtReasonOverview.Text.Trim
            updateKYC.AMLCDDOVERVIEW = lblLevelCom.Text.Trim
            updateKYC.AMLREASONOVERVIEW = txtReason.Text.Trim

            If Session("KYC") = 1 Then
                updateKYC.DEPUPDATE = "D"
            ElseIf Session("KYC") = 2 Then
                updateKYC.DEPUPDATE = "L"
            ElseIf Session("KYC") = 3 Then
                updateKYC.DEPUPDATE = "P"
            End If

            updateKYC.BRANCHCODE = clsSessionMenuRight.getBranchCode
            updateKYC.ZONECODE = clsSessionMenuRight.getZoneCode
            updateKYC.DEPTCODE = clsSessionMenuRight.getDeptCode
            updateKYC.ALLCODERIGHT = clsSessionMenuRight.getAllCodeRight


            updateKYC.UPDATEDATE = Now.ToShortDateString
        End If



    End Sub

    Private Sub SaveLog(ByVal index As Integer)
        Try
            Dim program As String = ""
            If CInt(Session("KYC")) = 1 Then
                program = "M12"
            ElseIf CInt(Session("KYC")) = 2 Then
                program = "M22"
            ElseIf CInt(Session("KYC")) = 3 Then
                program = "M32"
            Else
                program = "M42"
            End If

            Dim desc As String = ""
            If index = 1 Then
                desc = "พิมพ์ฟอร์ม KYC"
            ElseIf index = 2 Then
                desc = "พิมพ์ผลประเมินความเสี่ยง"
            ElseIf index = 3 Then
                desc = "บันทึก ผลประเมินความเสี่ยง (เลขทะเบียนนิติบุคคล " + txtBizNo.Text + ")"
            ElseIf index = 4 Then
                desc = "บันทึก แก้ไข ผลประเมินความเสี่ยง (เลขทะเบียนนิติบุคคล " + txtBizNo.Text + ")"

            End If

            Dim clsLogTransaction As New clsLogTransaction
            If index < 3 Then
                clsLogTransaction.saveLogTransaction(txtBizNo.Text.Trim, clsSessionMenuRight.getUserName, 2, desc, program)
            Else
                clsLogTransaction.saveLogTransaction(txtBizNo.Text.Trim, clsSessionMenuRight.getUserName, index, desc, program)
            End If
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region

#Region "Even GridView"

    Dim intBeforeItemIndex As Integer

    Protected Sub grdRef_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdRef.SelectedIndexChanged

        'If (grdRef.SelectedIndex = intBeforeItemIndex) Then
        '    grdRef.SelectedIndex = -1
        'End If

        'If Not grdRef.SelectedIndex = -1 Then
        '    If grdRef.Rows(grdRef.SelectedIndex).Cells(7).Text = 1 Then
        '        btnEdit.Attributes.Add("onclick", "window.showModalDialog('NonIndividualBoard.aspx?index=" & grdRef.SelectedIndex & "&TypeKYC=" & TypeKYC & "&CustSeq=" & ds.Tables("dsCustomerCom").Rows(grdRef.SelectedIndex)("CUSTSEQ") & "&UNIQUEID=" & ds.Tables("dsCustomerCom").Rows(grdRef.SelectedIndex)("UNIQUEID") & "', null, 'status:no; dialogWidth:1000px; dialogHeight:600px; help:no; scroll:yes; menubar:no; resizable:no')")
        '    Else
        '        btnEdit.Attributes.Add("onclick", "window.showModalDialog('NonIndividualBoardNon.aspx?index=" & grdRef.SelectedIndex & "&TypeKYC=" & TypeKYC & "&CustSeq=" & ds.Tables("dsCustomerCom").Rows(grdRef.SelectedIndex)("CUSTSEQ") & "&UNIQUEID=" & ds.Tables("dsCustomerCom").Rows(grdRef.SelectedIndex)("UNIQUEID") & "', null, 'status:no; dialogWidth:1000px; dialogHeight:600px; help:no; scroll:yes; menubar:no; resizable:no')")
        '    End If
        'End If

        'btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resMsgKYC.msgConfirmDelete) + "')")

    End Sub

    Protected Sub grdIndividual_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdRef.SelectedIndexChanging
        intBeforeItemIndex = grdRef.SelectedIndex
    End Sub

#End Region

    Protected Sub ddlApprove_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlApprove.SelectedIndexChanged
        If ddlApprove.SelectedIndex = 0 Then
            txtApproveNo.Enabled = False
            txtApprovePassword.Enabled = False
            txtApproveNo.Text = ""
            txtApprovePassword.Text = ""
        Else
            If ddlApprove.SelectedValue = 1 Then
                txtApproveNo.Enabled = False
                txtApprovePassword.Enabled = False
                txtApproveNo.Text = ""
                txtApprovePassword.Text = ""
            Else
                txtApproveNo.Enabled = True
                txtApprovePassword.Enabled = True
            End If
        End If
    End Sub

    Protected Sub btnKYCNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnKYCNext.Click
        Try
            If ds.Tables.Contains("GENKYC") Then
                ds.Tables.Remove("GENKYC")
            End If
            If CustSeq = 0 Then
                Response.Redirect("NonIndividualKYC.aspx?KYC=" & Session("KYC") & "&CUSTSEQ=0&CDD=0&TypeKYC=" & TypeKYC & "")
            Else
                If TypeKYC = 1 Then
                    If rdoAcc.SelectedIndex = 1 And ddlAcc.SelectedIndex > 0 Then
                        Response.Redirect("NonIndividualKYC.aspx?KYC=" & Session("KYC") & "&CUSTSEQ=" & Session("CUSTSEQ") & "&CDD=" & lblOverview.Text & "&TypeKYC=" & TypeKYC & "&acc=" & ddlAcc.SelectedItem.Text & "")
                    Else
                        Response.Redirect("NonIndividualKYC.aspx?KYC=" & Session("KYC") & "&CUSTSEQ=" & Session("CUSTSEQ") & "&CDD=" & lblOverview.Text & "&TypeKYC=" & TypeKYC & "")
                    End If

                    Response.Redirect("NonIndividualKYC.aspx?KYC=" & Session("KYC") & "&CUSTSEQ=" & Session("CUSTSEQ") & "&CDD=" & lblOverview.Text & "&TypeKYC=" & TypeKYC & "")
                Else
                    If rdoAcc.SelectedIndex = 1 And ddlAcc.SelectedIndex > 0 Then
                        Response.Redirect("NonIndividualKYC.aspx?KYC=" & Session("KYC") & "&CUSTSEQ=" & CustSeq & "&CDD=" & lblOverview.Text & "&TypeKYC=" & TypeKYC & "&acc=" & ddlAcc.SelectedItem.Text & "")
                    Else
                        Response.Redirect("NonIndividualKYC.aspx?KYC=" & Session("KYC") & "&CUSTSEQ=" & CustSeq & "&CDD=" & lblOverview.Text & "&TypeKYC=" & TypeKYC & "")
                    End If

                End If
            End If
        Catch ex As Exception

        End Try

    End Sub

    Protected Sub btnEditCompile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEditCompile.Click
        If (Panel1.Enabled = False) Then
            Panel1.Enabled = True
            btnCompile.Visible = True
            btnEditCompile.Visible = False
            btnReport.Visible = False
        Else
            Panel1.Enabled = False
            btnCompile.Visible = False
            btnEditCompile.Visible = True
            btnReport.Visible = True
        End If

    End Sub

    Protected Sub rdoAcc_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdoAcc.SelectedIndexChanged

        Dim intANSWERTYPE As Integer = 0

        If Request.QueryString("KYC") = 1 Then
            intANSWERTYPE = 2
        ElseIf Request.QueryString("KYC") = 2 Then
            intANSWERTYPE = 4
        ElseIf Request.QueryString("KYC") = 3 Then
            intANSWERTYPE = 6
        ElseIf Request.QueryString("KYC") = 4 Then
            intANSWERTYPE = 0
        End If

        If Not rdoAcc.SelectedIndex = 0 Then
            Dim AddItem As ListItem = Nothing
            AddItem = New ListItem(" กรุณาเลือกเลขที่บัญชี ", 0)
            Try
                hdfChkNewAcc.Value = 0
                If ds.Tables.Contains("ShowAccAll") Then
                    ddlAcc.DataSource = ds.Tables("ShowAccAll")
                    ddlAcc.DataValueField = "ACCOUNTNO"
                    ddlAcc.DataTextField = "ACCOUNTNO"
                    ddlAcc.DataBind()
                    If Not (AddItem Is Nothing) Then
                        ddlAcc.Items.Insert(0, AddItem)
                    End If
                    ddlAcc.SelectedIndex = 0

                Else
                    Dim clsDataTable As New clsLINQToDataTable
                    Dim qryRKYc = From tblKYC In KYCEntity.RKYC _
                                                       Where tblKYC.CUSTSEQ = CustSeq And Not (tblKYC.ACCOUNTNO = Nothing)
                                                       Select tblKYC.ANSWERTYPE, tblKYC.ACCOUNTNO


                    If Not intANSWERTYPE = 0 Then
                        qryRKYc = qryRKYc.Where(Function(fn) fn.ANSWERTYPE = intANSWERTYPE)
                    End If
                    If qryRKYc.Count > 0 Then
                        hdfChkNewAcc.Value = 1
                    End If


                    ds.Tables.Add(clsDataTable.LINQToDataTable(qryRKYc, "ShowAccAll").Copy)
                    ddlAcc.DataSource = ds.Tables("ShowAccAll")
                    ddlAcc.DataValueField = "ACCOUNTNO"
                    ddlAcc.DataTextField = "ACCOUNTNO"
                    ddlAcc.DataBind()
                    If Not (AddItem Is Nothing) Then
                        ddlAcc.Items.Insert(0, AddItem)
                    End If
                    ddlAcc.SelectedIndex = 0

                End If



                'If ds.Tables.Contains("RKYC_Acc") Then
                '    ds.Tables.Remove("RKYC_Acc")
                'End If

                'Dim qryRKYc = From tblKYC In KYCEntity.RKYC _
                '                                   Where tblKYC.CUSTSEQ = CustSeq
                '                                   Select tblKYC.ANSWERTYPE, tblKYC.ACCOUNTNO


                'If Not intANSWERTYPE = 0 Then
                '    qryRKYc = qryRKYc.Where(Function(fn) fn.ANSWERTYPE = intANSWERTYPE)
                'End If


                'ds.Tables.Add(clsDataTable.LINQToDataTable(qryRKYc, "RKYC_Acc").Copy)
                'ddlAcc.DataSource = ds.Tables("RKYC_Acc")
                'ddlAcc.DataValueField = "ACCOUNTNO"
                'ddlAcc.DataTextField = "ACCOUNTNO"
                'ddlAcc.DataBind()
                'If Not (AddItem Is Nothing) Then
                '    ddlAcc.Items.Insert(0, AddItem)
                'End If
                'ddlAcc.SelectedIndex = 0


            Catch ex As Exception

            End Try
            ddlAcc.Visible = True
        Else
            clsSessionMenuRight = Session("clsMenuRight")
            If Not TypeKYC = 1 Then

                Dim qryRKYc = From tblKYC In KYCEntity.RKYC _
                                       Where tblKYC.CUSTSEQ = CustSeq And _
                                             tblKYC.UPDATEBY = clsSessionMenuRight.getUserName And tblKYC.ACCOUNTNO = Nothing _
                                       Select tblKYC.ANSWERTYPE, tblKYC.ACCOUNTNO

                If Not intANSWERTYPE = 0 Then
                    qryRKYc = qryRKYc.Where(Function(fn) fn.ANSWERTYPE = intANSWERTYPE)
                End If



                If qryRKYc.Count = 0 Then
                    hdfChkNewAcc.Value = 0
                Else
                    hdfChkNewAcc.Value = 1
                End If
            Else
                hdfChkNewAcc.Value = 0
            End If



            ddlAcc.Visible = False


        End If
    End Sub

    Protected Sub txtSalaryPerMonth_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSalaryPerMonth.TextChanged
        Dim clsMoney As New clsMoney
        Dim condition As Boolean = True
        Try
            If Not txtSalaryPerMonth.Text = "" Then
                clsMoney = New clsMoney
                If clsMoney.insertComma(txtSalaryPerMonth.Text.Trim) = True Then
                    txtSalaryPerMonth.Text = clsMoney.insertComma(txtSalaryPerMonth.Text.Trim)

                End If
                clsMoney = Nothing
            End If
        Catch ex As Exception
            condition = False

            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & clsMoney.getStrMsg & "')", True)

        End Try
        clsMoney = Nothing
    End Sub

    Protected Sub rdoAnsSalary_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdoAnsSalary.SelectedIndexChanged

        If rdoAnsSalary.SelectedIndex = 0 Then

            txtSalaryPerMonth.Text = "0"
            txtSalaryPerMonth.Enabled = False
        Else
            txtSalaryPerMonth.Enabled = True
        End If
    End Sub

#Region "Misc 02"
    Protected Sub ddlNationality_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlNationality.SelectedIndexChanged
        If ddlNationality.SelectedValue <> "" Then
            If ddlNationality.SelectedValue = 202 Then Me.Set_Enable_Oth_Nat_Address_False() Else Me.Set_Enable_Oth_Nat_Address_True()
            Me.SElect_Risk_For_Nation()
        Else
            Me.Set_Enable_Oth_Nat_Address_False()
        End If
    End Sub

    Sub SElect_Risk_For_Nation()
        Dim dtRisk_Level As DataTable = New DataTable

        lvsSQL = ""
        lvsSQL += "     SELECT RISK                                                             "
        lvsSQL += "       FROM KYCADMIN.MNATIONALITY                                            "
        lvsSQL += "      WHERE NATIONCODE = '" & CInt(Me.ddlNationality.SelectedItem.Value) & "'"
        dtRisk_Level = clsDatabase.QueryDataTable(lvsSQL)

        If (dtRisk_Level.Rows.Count <> 0) Then
            If Not IsDBNull(dtRisk_Level.Rows(0)("RISK")) Then Me.lblRISK_LEVEL_NATION.Text = dtRisk_Level.Rows(0)("RISK")
        End If
    End Sub

    Sub Set_Enable_Politic_True()
        Me.lblF_POLITIC.Text = "Y"
        Me.btAddPolitical.Enabled = True
        Me.btDelPolitical.Enabled = True

        Me.txtPOLITIC_POST_SELF.Enabled = True
        Me.txtPOLITIC_RELATION.Enabled = True
        Me.txtPOLITIC_POST_CONC.Enabled = True
        Me.txtTHFIRSTNAME.Enabled = True
        Me.txtTHMIDNAME.Enabled = True
        Me.txtTHLASTNAME.Enabled = True

        Me.txtPOLITIC_POST_SELF.BackColor = Drawing.Color.White
        Me.txtPOLITIC_RELATION.BackColor = Drawing.Color.White
        Me.txtPOLITIC_POST_CONC.BackColor = Drawing.Color.White
        Me.txtTHFIRSTNAME.BackColor = Drawing.Color.White
        Me.txtTHMIDNAME.BackColor = Drawing.Color.White
        Me.txtTHLASTNAME.BackColor = Drawing.Color.White
    End Sub

    Sub Set_Enable_Politic_False()
        Me.btAddPolitical.Enabled = False
        Me.btDelPolitical.Enabled = False

        Me.txtPOLITIC_POST_SELF.Enabled = False : Me.txtPOLITIC_POST_SELF.Text = ""
        Me.txtPOLITIC_RELATION.Enabled = False : Me.txtPOLITIC_RELATION.Text = ""
        Me.txtPOLITIC_POST_CONC.Enabled = False : Me.txtPOLITIC_POST_CONC.Text = ""
        Me.txtTHFIRSTNAME.Enabled = False : Me.txtTHFIRSTNAME.Text = ""
        Me.txtTHMIDNAME.Enabled = False : Me.txtTHMIDNAME.Text = ""
        Me.txtTHLASTNAME.Enabled = False : Me.txtTHLASTNAME.Text = ""

        Me.txtPOLITIC_POST_SELF.BackColor = Drawing.Color.Silver
        Me.txtPOLITIC_RELATION.BackColor = Drawing.Color.Silver
        Me.txtPOLITIC_POST_CONC.BackColor = Drawing.Color.Silver
        Me.txtTHFIRSTNAME.BackColor = Drawing.Color.Silver
        Me.txtTHMIDNAME.BackColor = Drawing.Color.Silver
        Me.txtTHLASTNAME.BackColor = Drawing.Color.Silver
    End Sub
    Sub Set_Enable_Oth_Nat_Address_True()
        Me.txtOTH_NAT_ADD_1.Enabled = True : Me.txtOTH_NAT_ADD_1.BackColor = Drawing.Color.White
        Me.txtOTH_NAT_ADD_2.Enabled = True : Me.txtOTH_NAT_ADD_2.BackColor = Drawing.Color.White
        Me.txtOTH_NAT_ZIP.Enabled = True : Me.txtOTH_NAT_ZIP.BackColor = Drawing.Color.White
        Me.txtOTH_NAT_STREET.Enabled = True : Me.txtOTH_NAT_STREET.BackColor = Drawing.Color.White

        Me.txtOTH_NAT_PHN.Enabled = True : Me.txtOTH_NAT_PHN.BackColor = Drawing.Color.White
        Me.txtOTH_NAT_PHN_EXT.Enabled = True : Me.txtOTH_NAT_PHN_EXT.BackColor = Drawing.Color.White
        Me.txtOTH_NAT_MOBILE.Enabled = True : Me.txtOTH_NAT_MOBILE.BackColor = Drawing.Color.White
        Me.txtOTH_NAT_FAX.Enabled = True : Me.txtOTH_NAT_FAX.BackColor = Drawing.Color.White
        Me.txtOTH_NAT_EMAIL.Enabled = True : Me.txtOTH_NAT_EMAIL.BackColor = Drawing.Color.White

    End Sub

    Sub Set_Enable_Oth_Nat_Address_False()
        Me.txtOTH_NAT_ADD_1.Enabled = False : Me.txtOTH_NAT_ADD_1.BackColor = Drawing.Color.Silver : Me.txtOTH_NAT_ADD_1.Text = ""
        Me.txtOTH_NAT_ADD_2.Enabled = False : Me.txtOTH_NAT_ADD_2.BackColor = Drawing.Color.Silver : Me.txtOTH_NAT_ADD_2.Text = ""
        Me.txtOTH_NAT_ZIP.Enabled = False : Me.txtOTH_NAT_ZIP.BackColor = Drawing.Color.Silver : Me.txtOTH_NAT_ZIP.Text = ""
        Me.txtOTH_NAT_STREET.Enabled = False : Me.txtOTH_NAT_STREET.BackColor = Drawing.Color.Silver : Me.txtOTH_NAT_STREET.Text = ""

        Me.txtOTH_NAT_PHN.Enabled = False : Me.txtOTH_NAT_PHN.BackColor = Drawing.Color.Silver : Me.txtOTH_NAT_PHN.Text = ""
        Me.txtOTH_NAT_PHN_EXT.Enabled = False : Me.txtOTH_NAT_PHN_EXT.BackColor = Drawing.Color.Silver : Me.txtOTH_NAT_PHN_EXT.Text = ""
        Me.txtOTH_NAT_MOBILE.Enabled = False : Me.txtOTH_NAT_MOBILE.BackColor = Drawing.Color.Silver : Me.txtOTH_NAT_MOBILE.Text = ""
        Me.txtOTH_NAT_FAX.Enabled = False : Me.txtOTH_NAT_FAX.BackColor = Drawing.Color.Silver : Me.txtOTH_NAT_FAX.Text = ""
        Me.txtOTH_NAT_EMAIL.Enabled = False : Me.txtOTH_NAT_EMAIL.BackColor = Drawing.Color.Silver : Me.txtOTH_NAT_EMAIL.Text = ""

    End Sub
#End Region

#Region "Bind Data grid Corp Category"

    Sub Bind_Data_togrid_Corp_Category()

        '''' Connect Data to Grid '''''''''''

        Me.dtC_Cust_Category.Columns.Add("CAT_DESCRIPTION")
        Me.dtC_Cust_Category.Columns.Add("CAT_CODE")
        Me.dtC_Cust_Category.Columns.Add("REMARKS")
        Me.dtC_Cust_Category.Columns.Add("REMARKS_OTH")
        Me.dtC_Cust_Category.Columns.Add("RISK")
        Me.dtC_Cust_Category.Columns.Add("ACTIVE")

        Dim lvsCustType As Integer = Session("KYC")

        Dim QryOthDoc = (From tbName In KYCEntity.MCUST_C_CATE_TYPE
                           Where tbName.CUSTSEQ = CustSeq
                          Select tbName.SEQ,
                                 tbName.CAT_DESCRIPTION,
                                 tbName.CAT_CODE,
                                 tbName.REMARKS,
                                 tbName.RISK,
                                 tbName.REMARKS_OTH,
                                 ACTIVE = If(tbName.ACTIVE = "Y", True, False) Order By SEQ)

        For Each mRow In QryOthDoc
            Me.dtC_Cust_Category.Rows.Add(mRow.CAT_DESCRIPTION,
                                  mRow.CAT_CODE,
                                  mRow.REMARKS,
                                  mRow.REMARKS_OTH,
                                  mRow.RISK,
                                  mRow.ACTIVE)

            Me.dtC_Cust_Category.AcceptChanges()
        Next

        Me.grdCorp_Cate.DataSource = Me.dtC_Cust_Category
        Me.grdCorp_Cate.DataBind()

        ''''จำนวนแถว ''''''''''''''''''''''''''''''''''''''
        Me.lblCount_Corp_Cate.Text = Me.dtC_Cust_Category.Rows.Count
        ''''''''''''''''''''''''''''''''''''''''''''''''''

        Session("PopCorpCate") = Me.dtC_Cust_Category


    End Sub

    Protected Sub chACORP_CATE_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        ''''check Session ''''''''''''''''''''''
        If Not (Session("PopCorpCate") Is Nothing) Then
            Me.dtC_Cust_Category = Session("PopCorpCate")
        End If

        '''''' assign checkbox value to data table 
        For i = 0 To Me.grdCorp_Cate.Rows.Count - 1
            Me.dtC_Cust_Category.Rows(i).Item("ACTIVE") = CType(Me.grdCorp_Cate.Rows(i).Cells(5).FindControl("chACORP_CATE"), CheckBox).Checked
        Next i

        Me.dtC_Cust_Category.AcceptChanges()
        Me.grdCorp_Cate.DataSource = Me.dtC_Cust_Category
        Me.grdCorp_Cate.DataBind()

        Session("PopCorpCate") = Me.dtC_Cust_Category

    End Sub

    Protected Sub btnAdd_Corp_Cate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd_Corp_Cate.Click
        Me.Add_To_Grid_Corp_Cate()
    End Sub

    Sub Add_To_Grid_Corp_Cate()

        If Validate_Corp_Cate() = False Then Exit Sub

        'check session of data table
        If Not (Session("PopCorpCate") Is Nothing) Then
            Me.dtC_Cust_Category = Session("PopCorpCate")
        End If

        '''''''' insert data to grid row '''''''''''''''''''''''''''''''''''''''''''''''''

        '''''''''''''
        Dim dtRisk_Level As DataTable = New DataTable
        Dim lvsRisk As Integer = 1

        lvsSQL = ""
        lvsSQL += "     SELECT RISK                                                          "
        lvsSQL += "       FROM KYCADMIN.MBUSINESS                                            "
        lvsSQL += "      WHERE BIZCODE = '" & CInt(Me.ddlNationality.SelectedItem.Value) & "'"

        dtRisk_Level = clsDatabase.QueryDataTable(lvsSQL)

        If (dtRisk_Level.Rows.Count <> 0) Then
            If Not IsDBNull(dtRisk_Level.Rows(0)("RISK")) Then lvsRisk = dtRisk_Level.Rows(0)("RISK")
        End If
        ''''''''''

        Me.dtC_Cust_Category.Rows.Add(Me.ddlBusiness1.SelectedItem,
                              Me.ddlBusiness1.SelectedValue,
                              Me.txtCorp_Cate_Remarks.Text,
                              Me.txtBizOther1.Text,
                              lvsRisk,
                              True)

        Me.dtC_Cust_Category.AcceptChanges()
        Me.grdCorp_Cate.DataSource = Me.dtC_Cust_Category
        Me.grdCorp_Cate.DataBind()

        ''''จำนวนแถว ''''''''''''''''''''''''''''''''''''''
        Me.lblCount_Corp_Cate.Text = Me.dtC_Cust_Category.Rows.Count
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        ' Me.ddlBusiness1.SelectedIndex = -1
        Me.txtCorp_Cate_Remarks.Text = ""
        Me.ddlBusiness1.Focus()
    End Sub

    Function Validate_Corp_Cate() As Boolean

        Validate_Corp_Cate = False

        If Me.ddlBusiness1.SelectedIndex <= 0 Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage",
                                                "window.alert('กรูณาเลือกประเภทธุรกิจ');", True)
            ddlBusiness1.Focus()
            Exit Function

        End If

        ''''''''Validate ข้อมูลซ้ำ''''''''''''''''''
        Dim mDocType As String = ""
        For Each rowFromGrid As GridViewRow In Me.grdCorp_Cate.Rows

            mDocType = rowFromGrid.Cells(1).Text

            If mDocType = Me.ddlBusiness1.SelectedItem.Text Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ข้อมูลซ้ำ ! กรูณาเลือกประเภทธุรกิจอื่น');", True)
                ddlBusiness1.Focus()
                Exit Function
            End If

        Next
        '''''''''''''''''''''''''''''

        If clsValid.CheckNull(Me.txtCorp_Cate_Remarks) = False Then Exit Function
        Validate_Corp_Cate = True
    End Function

    Protected Sub Save_to_MCUST_C_CATE_TYPE(ByVal key As Integer)

        Dim mCAT_DESCRIPTION As String = ""
        Dim mCAT_CODE As String = ""
        Dim mREMARKS As String = ""
        Dim mREMARKS_OTH As String = ""
        Dim mRISK As String = ""
        Dim chActive As String = ""
        Dim lvsCustType As Integer = Session("KYC")
        '''''''''''''''''''''''

        Try

            Dim DeletedQuery = (From m In KYCEntity.MCUST_C_CATE_TYPE
                               Where m.CUSTSEQ = key _
                              Select m).ToList

            If DeletedQuery.Count > 0 Then
                For i As Integer = 0 To DeletedQuery.Count - 1
                    KYCEntity.MCUST_C_CATE_TYPE.DeleteObject(DeletedQuery(i))
                Next i
            End If
            ''''''''''''''''''''''
            For Each lvsRow_No As GridViewRow In Me.grdCorp_Cate.Rows
                Dim newMCUST_C_CATE_TYPE As New MCUST_C_CATE_TYPE


                ''''get values from Gridview '''''''
                mCAT_DESCRIPTION = lvsRow_No.Cells(1).Text : If mCAT_DESCRIPTION = "&nbsp;" Then mCAT_DESCRIPTION = ""
                mCAT_CODE = lvsRow_No.Cells(2).Text : If mCAT_CODE = "&nbsp;" Then mCAT_CODE = ""
                mREMARKS = lvsRow_No.Cells(3).Text : If mREMARKS = "&nbsp;" Then mREMARKS = ""
                mREMARKS_OTH = lvsRow_No.Cells(4).Text : If mREMARKS_OTH = "&nbsp;" Then mREMARKS_OTH = ""
                mRISK = lvsRow_No.Cells(5).Text : If mRISK = "&nbsp;" Then mRISK = ""

                If (CType(lvsRow_No.Cells(6).FindControl("chACORP_CATE"), CheckBox).Checked = True) Then
                    chActive = "Y"
                Else
                    chActive = "N"
                End If

                ''''''''''''''''''''''''''''''''''''

                '''''''LINQ Start here ''''''''''''''
                newMCUST_C_CATE_TYPE.CUSTSEQ = key
                newMCUST_C_CATE_TYPE.CUSTTYPE = Session("KYC")
                newMCUST_C_CATE_TYPE.SEQ = lvsRow_No.RowIndex + 1
                newMCUST_C_CATE_TYPE.CAT_DESCRIPTION = mCAT_DESCRIPTION.Trim
                newMCUST_C_CATE_TYPE.CAT_CODE = mCAT_CODE.Trim
                newMCUST_C_CATE_TYPE.REMARKS = mREMARKS.Trim
                newMCUST_C_CATE_TYPE.REMARKS_OTH = mREMARKS_OTH.Trim
                newMCUST_C_CATE_TYPE.RISK = mRISK.Trim
                newMCUST_C_CATE_TYPE.ACTIVE = chActive
                newMCUST_C_CATE_TYPE.CREATED_DATE = Now
                newMCUST_C_CATE_TYPE.CREATED_BY = clsSessionMenuRight.getUserName
                KYCEntity.AddToMCUST_C_CATE_TYPE(newMCUST_C_CATE_TYPE)
            Next
            KYCEntity.SaveChanges()

        Catch ex As Exception
            Throw ex

        End Try

    End Sub

    Protected Sub btnDel_Corp_Cate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDel_Corp_Cate.Click
        Delete_gridRow_grdCorp_Cate()
    End Sub

    Sub Delete_gridRow_grdCorp_Cate()
        Try

            Dim index As Integer = grdCorp_Cate.SelectedIndex
            If index = -1 Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "clientScript", "alert('ต้องเลือกเลขที่ประเภทธุรกิจที่ต้องการลบก่อน')", True)
            Else
                'check session of data table
                If Not (Session("PopCorpCate") Is Nothing) Then
                    Me.dtC_Cust_Category = Session("PopCorpCate")
                End If
                ''''remove row at...
                dtC_Cust_Category.Rows.RemoveAt(index)
                dtC_Cust_Category.AcceptChanges()

                ''''bind data again
                grdCorp_Cate.DataSource = dtC_Cust_Category
                grdCorp_Cate.DataBind()
                ''''จำนวนแถว ''''''''''''''''''''''''''''''''''''''
                Me.lblCount_Corp_Cate.Text = Me.dtC_Cust_Category.Rows.Count
                ''''''''''''''''''''''''''''''''''''''''''''''''''
                ''''deselect ''''''''''''''''''''
                grdCorp_Cate.SelectedIndex = -1
            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Page,
                                                Page.GetType(),
                                                "clientScript",
                                                "alert('" + ex.Message.Replace("'", "") + "')",
                                                True)
        End Try
    End Sub

    Protected Sub grdCorp_Cate_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdCorp_Cate.SelectedIndexChanged
        If grdCorp_Cate.SelectedIndex = intBeforeSelectIndex_Corp_Cate Then
            grdCorp_Cate.SelectedIndex = -1
        End If
    End Sub

    Protected Sub grdCorp_Cate_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdCorp_Cate.SelectedIndexChanging
        intBeforeSelectIndex_Corp_Cate = grdCorp_Cate.SelectedIndex
    End Sub

#End Region


#Region "Validate Before Save "

    Function Validate_For_All() As Boolean
        Validate_For_All = False

        Panel1.Enabled = True


        If Me.DdOtherID.SelectedValue <> "" Then
            If clsValid.CheckNull(Me.txtTYPEEVIDENCE_NO) = False Then Exit Function
        End If

        ''''''''''Birth Date '''''''''''''''''''''''''''''''''''''''''''''''''''
        If clsValid.CheckNull(Me.txtBIRTH_DATE_TH_DD) = False Then Exit Function
        If clsValid.CheckNull(Me.txtBIRTH_DATE_TH_MM) = False Then Exit Function
        If clsValid.CheckNull(Me.txtBIRTH_DATE_TH_YYYY) = False Then Exit Function

        If (clsValid.CheckNumdayInMonth(txtBIRTH_DATE_TH_DD) = False) Then Exit Function
        If (clsValid.CheckMonthOfYear(Me.txtBIRTH_DATE_TH_MM) = False) Then Exit Function
        If (clsValid.CheckYear_TH(Me.txtBIRTH_DATE_TH_YYYY) = False) Then Exit Function
        Me.lbBIRTH_DATE_TH.Text = clsValid.ConcatDate(Me.txtBIRTH_DATE_TH_DD.Text,
                                                      Me.txtBIRTH_DATE_TH_MM.Text,
                                                      Me.txtBIRTH_DATE_TH_YYYY.Text)



        Me.lbBIRTH_DATE_Check.Text = clsValid.ConcatDate(Me.txtBIRTH_DATE_TH_DD.Text,
                                                         Me.txtBIRTH_DATE_TH_MM.Text,
                                                         CInt(Me.txtBIRTH_DATE_TH_YYYY.Text) - 544)

        If (clsValid.CheckDate(lbBIRTH_DATE_Check) = False) Then
            Me.txtBIRTH_DATE_TH_DD.Focus() : Exit Function
        End If

        Me.txtBIRTH_DATE_EN_DD.Text = Me.txtBIRTH_DATE_TH_DD.Text
        Me.txtBIRTH_DATE_EN_MM.Text = Me.txtBIRTH_DATE_TH_MM.Text
        Me.txtBIRTH_DATE_EN_YYYY.Text = CInt(Me.txtBIRTH_DATE_TH_YYYY.Text) - 543

        Me.lbBIRTH_DATE_EN.Text = (clsValid.ConcatDate(Me.txtBIRTH_DATE_EN_DD.Text,
                                                       Me.txtBIRTH_DATE_EN_MM.Text,
                                                       CInt(Me.txtBIRTH_DATE_EN_YYYY.Text)))
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        If CInt(Me.lblCount_Corp_Cate.Text) = 0 Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('กรุณาป้อนข้อมูลประเภทธุรกิจให้ครบถ้วน');", True)
            Me.ddlBusiness1.Focus()
            Exit Function
        End If

        If Me.optPOL_CONNECT_Y.Checked = True Then
            Me.lblF_POLITIC.Text = "Y"
        Else
            Me.lblF_POLITIC.Text = "N"
        End If

        If Me.lblF_POLITIC.Text = "Y" And CInt(Me.lblCount_Politic.Text) = 0 Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('กรุณาป้อนข้อมูลบุคคลที่เกี่ยวข้องกับนักการเมืองให้ครบถ้วน');", True)
            Me.optPOL_CONNECT_Y.Focus()
            Exit Function
        ElseIf Me.lblF_POLITIC.Text = "N" And CInt(Me.lblCount_Politic.Text) <> 0 Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ข้อมูลขัดแย้ง ! กรุณาเลือก-มีความสัมพันธ์กรณีที่เกี่ยวข้องกับการเมือง-หรือข้อมูลบุคคลที่เกี่ยวข้องกับนักการเมือง');", True)
            Me.optPOL_CONNECT_Y.Focus()
            Exit Function
        End If
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


        Validate_For_All = True
        Panel1.Enabled = False
    End Function

#End Region

#Region "นักการเมือง"

    Protected Sub optPOL_CONNECT_N_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles optPOL_CONNECT_N.CheckedChanged
        Me.lblF_POLITIC.Text = "N"
        Me.Set_Enable_Politic_False()
    End Sub

    Protected Sub optPOL_CONNECT_Y_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles optPOL_CONNECT_Y.CheckedChanged
        Me.lblF_POLITIC.Text = "Y"
        Me.Set_Enable_Politic_True()
    End Sub

    Sub Bind_Data_togrid_grdPolitical()

        '''' Connect Data to Grid '''''''''''
        Me.dtPolitical.Columns.Add("THPREFIX")
        Me.dtPolitical.Columns.Add("THPREFIX_DESC")
        Me.dtPolitical.Columns.Add("THFIRSTNAME")
        Me.dtPolitical.Columns.Add("THMIDNAME")
        Me.dtPolitical.Columns.Add("THLASTNAME")

        Me.dtPolitical.Columns.Add("ENPREFIX")
        Me.dtPolitical.Columns.Add("ENPREFIX_DESC")
        Me.dtPolitical.Columns.Add("ENFIRSTNAME")
        Me.dtPolitical.Columns.Add("ENMIDNAME")
        Me.dtPolitical.Columns.Add("ENLASTNAME")

        Me.dtPolitical.Columns.Add("POLITIC_POST_CONC")
        Me.dtPolitical.Columns.Add("POLITIC_RELATION")
        Me.dtPolitical.Columns.Add("ACTIVE")

        Dim lvsCustType As Integer = Session("KYC")

        Dim qryPolitic = (From tbName In KYCEntity.MCUST_POLITICIAN_CONCERN
                        Where tbName.CUSTSEQ = CustSeq
                       Select tbName.SEQ,
                              tbName.THPREFIX,
                              tbName.THPREFIX_DESC,
                              tbName.THFIRSTNAME,
                              tbName.THMIDNAME,
                              tbName.THLASTNAME,
                              tbName.ENPREFIX,
                              tbName.ENPREFIX_DESC,
                              tbName.ENFIRSTNAME,
                              tbName.ENMIDNAME,
                              tbName.ENLASTNAME,
                              tbName.POLITIC_RELATION,
                              tbName.POLITIC_POST_CONC,
                              ACTIVE = If(tbName.ACTIVE = "Y", True, False)
                     Order By SEQ)

        For Each mRow In qryPolitic
            Me.dtPolitical.Rows.Add(mRow.THPREFIX,
                                    mRow.THPREFIX_DESC,
                                    mRow.THFIRSTNAME,
                                    mRow.THMIDNAME,
                                    mRow.THLASTNAME,
                                    mRow.ENPREFIX,
                                    mRow.ENPREFIX_DESC,
                                    mRow.ENFIRSTNAME,
                                    mRow.THMIDNAME,
                                    mRow.ENLASTNAME,
                                    mRow.POLITIC_POST_CONC,
                                    mRow.POLITIC_RELATION,
                                    mRow.ACTIVE)
            Me.dtPolitical.AcceptChanges()
        Next

        Me.grdPolitical.DataSource = Me.dtPolitical
        Me.grdPolitical.DataBind()
        ''''Number of Rows '''''''''''''''''''''''''''''''''' 
        Me.lblCount_Politic.Text = Me.dtPolitical.Rows.Count
        '''''''''''''''''''''''''''''''''''''''''''''''''''''
        Session("PopPolitical") = Me.dtPolitical

    End Sub

    Protected Sub chk_ACT_POLTIC_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        ''''check Session ''''''''''''''''''''''
        If Not (Session("PopPolitical") Is Nothing) Then
            Me.dtPolitical = Session("PopPolitical")
        End If

        '''''' assign checkbox value to data table 
        For i = 0 To Me.grdPolitical.Rows.Count - 1
            Me.dtPolitical.Rows(i).Item("ACTIVE") = CType(Me.grdPolitical.Rows(i).Cells(6).FindControl("chk_ACT_POLTIC"), CheckBox).Checked
        Next i

        Me.dtPolitical.AcceptChanges()
        Me.grdPolitical.DataSource = Me.dtPolitical
        Me.grdPolitical.DataBind()

        Session("PopPolitical") = Me.dtPolitical

    End Sub

    Protected Sub btAddPolitical_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btAddPolitical.Click
        Me.Add_To_grid_Politic()
    End Sub

    Function Validate_Potician_Concern() As Boolean
        Validate_Potician_Concern = False
        If clsValid.CheckNull(Me.txtPOLITIC_RELATION) = False Then Exit Function
        If clsValid.CheckNull(Me.txtPOLITIC_POST_CONC) = False Then Exit Function
        If clsValid.CheckNull(Me.txtTHFIRSTNAME) = False Then Exit Function
        If clsValid.CheckNull(Me.txtTHLASTNAME) = False Then Exit Function
        Validate_Potician_Concern = True
    End Function

    Sub Add_To_grid_Politic()

        If Validate_Potician_Concern() = False Then Exit Sub

        'check session of data table
        If Not (Session("PopPolitical") Is Nothing) Then
            Me.dtPolitical = Session("PopPolitical")
        End If

        '''''''' insert data to grid row '''''''''''''''''''''''''''''''''''''''''''''''''
        dtPolitical.Rows.Add(Me.ddlPrefixTH_POLITIC.SelectedValue,
                             Me.ddlPrefixTH_POLITIC.SelectedItem,
                             Me.txtTHFIRSTNAME.Text,
                             Me.txtTHMIDNAME.Text,
                             Me.txtTHLASTNAME.Text,
                             Me.ddlPrefixEN_POLITIC.SelectedValue,
                             Me.ddlPrefixEN_POLITIC.SelectedItem,
                             Me.txtenFIRSTNAME.Text,
                             Me.txtENMIDNAME.Text,
                             Me.txtENLASTNAME.Text,
                             Me.txtPOLITIC_POST_CONC.Text,
                             Me.txtPOLITIC_RELATION.Text,
                             True)
        dtPolitical.AcceptChanges()
        Me.grdPolitical.DataSource = dtPolitical
        Me.grdPolitical.DataBind()
        ''''Number of Rows '''''''''''''''''''''''''''''''''' 
        Me.lblCount_Politic.Text = Me.dtPolitical.Rows.Count
        '''''''''''''''''''''''''''''''''''''''''''''''''''''

        ''''deselect 
        Me.grdPolitical.SelectedIndex = -1

        'now bind datatable to gridview... 
        Session("PopPolitical") = Me.dtPolitical

        ''''''clear screen
        Me.txtPOLITIC_RELATION.Text = ""
        Me.txtPOLITIC_POST_CONC.Text = ""
        Me.txtTHFIRSTNAME.Text = ""
        Me.txtTHMIDNAME.Text = ""
        Me.txtTHLASTNAME.Text = ""

        Me.txtPOLITIC_RELATION.Focus()

    End Sub

    Protected Sub btDelPolitical_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btDelPolitical.Click
        Delete_gridRow_grdPolitical()
    End Sub

    Sub Delete_gridRow_grdPolitical()
        Try

            Dim index As Integer = grdPolitical.SelectedIndex
            If index = -1 Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "clientScript", "alert('ต้องเลือกชื่อนักการเมืองที่ต้องการลบก่อน')", True)
            Else
                'check session of data table
                If Not (Session("PopPolitical") Is Nothing) Then
                    Me.dtPolitical = Session("PopPolitical")
                End If
                ''''remove row at...
                dtPolitical.Rows.RemoveAt(index)
                dtPolitical.AcceptChanges()

                ''''bind data again
                grdPolitical.DataSource = dtPolitical
                grdPolitical.DataBind()
                ''''Number of Rows '''''''''''''''''''''''''''''''''' 
                Me.lblCount_Politic.Text = Me.dtPolitical.Rows.Count
                '''''''''''''''''''''''''''''''''''''''''''''''''''''
                ''''deselect''''''''''''''''''''' 
                grdPolitical.SelectedIndex = -1
                '''''''''''''''''''''''''''''''''
                '  Me.lblAuthor_Req_Politic.Text = "Y"

            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Page,
                                                Page.GetType(),
                                                "clientScript",
                                                "alert('" + ex.Message.Replace("'", "") + "')",
                                                True)
        End Try
    End Sub

    Protected Sub grdPolitical_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdPolitical.SelectedIndexChanged
        If grdPolitical.SelectedIndex = intBeforeSelectIndex_Politician Then
            grdPolitical.SelectedIndex = -1
        End If
    End Sub

    Protected Sub grdPolitical_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdPolitical.SelectedIndexChanging
        Me.intBeforeSelectIndex_Politician = grdPolitical.SelectedIndex
    End Sub

    Protected Sub Save_to_Cust_Politician(ByVal key As Integer)

        Dim mPolician_Prefix_TH As String = ""
        Dim mPolician_Prefix_Desc_TH As String = ""
        Dim mPolician_Name_TH As String = ""
        Dim mPolician_MidName_TH As String = ""
        Dim mPolician_Surname_TH As String = ""

        Dim mPolician_Prefix_EN As String = ""
        Dim mPolician_Prefix_Desc_EN As String = ""
        Dim mPolician_Name_EN As String = ""
        Dim mPolician_MidName_EN As String = ""
        Dim mPolician_Surname_EN As String = ""

        Dim mPolician_Position As String = ""
        Dim mPolician_Relation As String = ""
        Dim chActive As String = ""

        Dim lvsCustType As Integer = Session("KYC")
        '''''''''''''''''''''''

        Try

            Dim DeletedQuery = (From m In KYCEntity.MCUST_POLITICIAN_CONCERN
                               Where m.CUSTSEQ = key _
                              Select m).ToList

            If DeletedQuery.Count > 0 Then
                For i As Integer = 0 To DeletedQuery.Count - 1
                    KYCEntity.MCUST_POLITICIAN_CONCERN.DeleteObject(DeletedQuery(i))
                Next i
            End If
            ''''''''''''''''''''''
            For Each lvsRow_No As GridViewRow In Me.grdPolitical.Rows
                Dim newCust_Politician As New MCUST_POLITICIAN_CONCERN

                ''''get values from Gridview '''''''
                mPolician_Prefix_TH = lvsRow_No.Cells(1).Text : If mPolician_Prefix_TH = "&nbsp;" Then mPolician_Prefix_TH = ""
                mPolician_Prefix_Desc_TH = lvsRow_No.Cells(2).Text : If mPolician_Prefix_Desc_TH = "&nbsp;" Then mPolician_Prefix_Desc_TH = ""
                mPolician_Name_TH = lvsRow_No.Cells(3).Text : If mPolician_Name_TH = "&nbsp;" Then mPolician_Name_TH = ""
                mPolician_MidName_TH = lvsRow_No.Cells(4).Text : If mPolician_MidName_TH = "&nbsp;" Then mPolician_MidName_TH = ""
                mPolician_Surname_TH = lvsRow_No.Cells(5).Text : If mPolician_Surname_TH = "&nbsp;" Then mPolician_Surname_TH = ""

                mPolician_Prefix_EN = lvsRow_No.Cells(6).Text : If mPolician_Prefix_EN = "&nbsp;" Then mPolician_Prefix_EN = ""
                mPolician_Prefix_Desc_EN = lvsRow_No.Cells(7).Text : If mPolician_Prefix_Desc_EN = "&nbsp;" Then mPolician_Prefix_Desc_EN = ""
                mPolician_Name_EN = lvsRow_No.Cells(8).Text : If mPolician_Name_EN = "&nbsp;" Then mPolician_Name_EN = ""
                mPolician_MidName_EN = lvsRow_No.Cells(9).Text : If mPolician_MidName_EN = "&nbsp;" Then mPolician_MidName_EN = ""
                mPolician_Surname_EN = lvsRow_No.Cells(10).Text : If mPolician_Surname_EN = "&nbsp;" Then mPolician_Surname_EN = ""

                mPolician_Position = lvsRow_No.Cells(11).Text : If mPolician_Position = "&nbsp;" Then mPolician_Position = ""
                mPolician_Relation = lvsRow_No.Cells(12).Text : If mPolician_Relation = "&nbsp;" Then mPolician_Relation = ""


                If (CType(lvsRow_No.Cells(13).FindControl("chk_ACT_POLTIC"), CheckBox).Checked = True) Then
                    chActive = "Y"
                Else
                    chActive = "N"
                End If

                ''''''''''''''''''''''''''''''''''''


                '''''''LINQ Start here '''''''''''''
                newCust_Politician.CUSTSEQ = key
                newCust_Politician.CUSTTYPE = Session("KYC")
                newCust_Politician.SEQ = lvsRow_No.RowIndex + 1

                newCust_Politician.THPREFIX = CInt(mPolician_Prefix_TH.Trim)
                newCust_Politician.THPREFIX_DESC = mPolician_Prefix_Desc_TH.Trim
                newCust_Politician.THFIRSTNAME = mPolician_Name_TH.Trim
                newCust_Politician.THMIDNAME = mPolician_MidName_TH.Trim
                newCust_Politician.THLASTNAME = mPolician_Surname_TH.Trim

                newCust_Politician.ENPREFIX = CInt(mPolician_Prefix_EN.Trim)
                newCust_Politician.ENPREFIX_DESC = mPolician_Prefix_Desc_EN.Trim
                newCust_Politician.ENFIRSTNAME = mPolician_Name_EN.Trim
                newCust_Politician.ENMIDNAME = mPolician_MidName_EN.Trim
                newCust_Politician.ENLASTNAME = mPolician_Surname_EN.Trim

                newCust_Politician.POLITIC_RELATION = mPolician_Relation.Trim
                newCust_Politician.POLITIC_POST_CONC = mPolician_Position.Trim
                newCust_Politician.ACTIVE = chActive
                newCust_Politician.CREATED_DATE = Now
                newCust_Politician.CREATED_BY = clsSessionMenuRight.getUserName
                KYCEntity.AddToMCUST_POLITICIAN_CONCERN(newCust_Politician)
            Next
            KYCEntity.SaveChanges()

        Catch ex As Exception
            Throw ex

        End Try


    End Sub

#End Region

#Region "Reason"

    Sub Bind_Data_togrid_Reason()

        '''' Connect Data to Grid '''''''''''
        Me.dtReason.Columns.Add("USER_CREATED_DATE")
        Me.dtReason.Columns.Add("USER_CREATED_BY")
        Me.dtReason.Columns.Add("REASONS")
        Me.dtReason.Columns.Add("ACTIVE")

        Dim lvsCustType As Integer = Session("KYC")

        Dim qryReason = (From tbName In KYCEntity.MCUST_REASON
                        Where tbName.CUSTSEQ = CustSeq
                       Select tbName.SEQ,
                              tbName.USER_CREATED_DATE,
                              tbName.USER_CREATED_BY,
                              tbName.REASONS,
                              ACTIVE = If(tbName.ACTIVE = "Y", True, False)
                     Order By SEQ)

        For Each mRow In qryReason
            Me.dtReason.Rows.Add(mRow.USER_CREATED_DATE,
                                 mRow.USER_CREATED_BY,
                                 mRow.REASONS,
                                 mRow.ACTIVE)

            Me.dtReason.AcceptChanges()
        Next

        Me.grdReason.DataSource = Me.dtReason
        Me.grdReason.DataBind()
        ''''Number of Rows''''''''''''''''''''''''''''''
        Me.lblCount_Reason.Text = Me.dtReason.Rows.Count
        ''''''''''''''''''''''''''''''''''''''''''''''''
        Session("PopReason") = Me.dtReason

    End Sub

    Protected Sub chk_ACT_REASON_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        ''''check Session ''''''''''''''''''''''
        If Not (Session("PopReason") Is Nothing) Then
            Me.dtReason = Session("PopReason")
        End If

        '''''' assign checkbox value to data table 
        For i = 0 To Me.grdReason.Rows.Count - 1
            Me.dtReason.Rows(i).Item("ACTIVE") = CType(Me.grdReason.Rows(i).Cells(4).FindControl("chk_ACT_REASON"), CheckBox).Checked
        Next i

        Me.dtReason.AcceptChanges()
        Me.grdReason.DataSource = Me.dtReason
        Me.grdReason.DataBind()

        Session("PopReason") = Me.dtReason


    End Sub

    Protected Sub btAddReason_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btAddReason.Click
        Add_To_grid_Reason()
    End Sub

    Function Validate_Reason() As Boolean
        Validate_Reason = False
        If clsValid.CheckNull(Me.txtReasonApp) = False Then Exit Function
        Validate_Reason = True
    End Function

    Sub Add_To_grid_Reason()

        If Validate_Reason() = False Then Exit Sub

        'check session of data table
        If Not (Session("PopReason") Is Nothing) Then
            Me.dtReason = Session("PopReason")
        End If
        Dim strUser As String = clsSessionMenuRight.getUserName

        '''''''' insert data to grid row '''''''''''''''''''''''''''''''''''''''''''''''''
        dtReason.Rows.Add(Now,
                          strUser,
                          Me.txtReasonApp.Text,
                          True)

        dtReason.AcceptChanges()
        Me.grdReason.DataSource = Me.dtReason
        Me.grdReason.DataBind()

        ''''Number of Rows''''''''''''''''''''''''''''''
        Me.lblCount_Reason.Text = Me.dtReason.Rows.Count
        ''''''''''''''''''''''''''''''''''''''''''''''''

        ''''deselect 
        Me.grdReason.SelectedIndex = -1

        'now bind datatable to gridview... 
        Session("PopReason") = Me.dtReason

        ''''Clear Screen ''''''''''''
        Me.txtReasonApp.Text = ""
        Me.txtReasonApp.Focus()
    End Sub

    Protected Sub btDelReason_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btDelReason.Click
        Delete_gridRow_grdReason()
    End Sub

    Sub Delete_gridRow_grdReason()
        Try

            Dim index As Integer = grdReason.SelectedIndex
            If index = -1 Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "clientScript", "alert('ต้องเลือกข้อมูลเหตุผลที่ต้องการลบก่อน')", True)
            Else
                'check session of data table
                If Not (Session("PopReason") Is Nothing) Then
                    Me.dtReason = Session("PopReason")
                End If
                ''''remove row at...
                dtReason.Rows.RemoveAt(index)
                dtReason.AcceptChanges()

                ''''bind data again
                grdReason.DataSource = dtReason
                grdReason.DataBind()
                ''''Number of Rows''''''''''''''''''''''''''''''
                Me.lblCount_Reason.Text = Me.dtReason.Rows.Count
                ''''''''''''''''''''''''''''''''''''''''''''''''
                ''''deselect '''''''''''''''
                grdReason.SelectedIndex = -1
                '''''''''''''''''''''''''''''
            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Page, _
                                                            Page.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)
        End Try
    End Sub

    Protected Sub grdReason_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdReason.SelectedIndexChanged
        If grdReason.SelectedIndex = intBeforeSelectIndex_Reason Then
            grdReason.SelectedIndex = -1
        End If
    End Sub

    Protected Sub grdReason_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdReason.SelectedIndexChanging
        Me.intBeforeSelectIndex_Reason = grdReason.SelectedIndex
    End Sub

    Protected Sub Save_to_Cust_Reason(ByVal key As Integer)

        Dim mUser_Created_Date As String = ""
        Dim mUser_Created_By As String = ""
        Dim mUser_Reason As String = ""
        Dim chActive As String = ""
        Dim lvsCustType As Integer = Session("KYC")
        '''''''''''''''''''''''

        Try

            Dim DeletedQuery = (From m In KYCEntity.MCUST_REASON
                               Where m.CUSTSEQ = key _
                              Select m).ToList

            If DeletedQuery.Count > 0 Then
                For i As Integer = 0 To DeletedQuery.Count - 1
                    KYCEntity.MCUST_REASON.DeleteObject(DeletedQuery(i))
                Next i
            End If
            ''''''''''''''''''''''
            For Each rowID As GridViewRow In grdReason.Rows
                Dim newCust_Reason As New MCUST_REASON

                ''''get values from Gridview '''''''
                mUser_Reason = rowID.Cells(1).Text : If mUser_Reason = "&nbsp;" Then mUser_Reason = ""
                mUser_Created_Date = rowID.Cells(2).Text : If mUser_Created_Date = "&nbsp;" Then mUser_Created_Date = ""
                mUser_Created_By = rowID.Cells(3).Text : If mUser_Created_By = "&nbsp;" Then mUser_Created_By = ""

                If (CType(rowID.Cells(4).FindControl("chk_ACT_REASON"), CheckBox).Checked = True) Then
                    chActive = "Y"
                Else
                    chActive = "N"
                End If


                ''''''''''''''''''''''''''''''''''''

                '''''''LINQ Start here ''''''''''''''
                newCust_Reason.CUSTSEQ = key
                newCust_Reason.CUSTTYPE = Session("KYC")
                newCust_Reason.SEQ = rowID.RowIndex + 1
                newCust_Reason.REASONS = Mid(mUser_Reason, 1, 150)
                newCust_Reason.USER_CREATED_DATE = mUser_Created_Date
                newCust_Reason.USER_CREATED_BY = mUser_Created_By
                newCust_Reason.ACTIVE = chActive
                newCust_Reason.CREATED_DATE = Now
                newCust_Reason.CREATED_BY = clsSessionMenuRight.getUserName
                KYCEntity.AddToMCUST_REASON(newCust_Reason)
            Next
            KYCEntity.SaveChanges()
        Catch ex As Exception
            Throw ex
            'Catch ex As System.Data.SqlClient.SqlException
            '    Dim lvsERROR As String = ex.Message.ToString
            '    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" & lvsERROR & "')", True)
        End Try




    End Sub

    Protected Sub Save_to_Cust_SanctList(ByVal key As Integer)

        Dim chActive As String = ""
        Dim mENTITY_ID As String = ""
        Dim mFAM_UniqueID As String = ""
        Dim mFIRSTNAME_E As String = ""
        Dim mMIDDLE_NAME_E As String = ""
        Dim mSURNAME_E As String = ""
        Dim mFullName As String = ""
        Dim mFIRST_NAME As String = ""
        Dim mMID_NAME As String = ""
        Dim mSURNAME As String = ""
        Dim mORIGINAL_SCRIPT_NAME As String = ""
        Dim mBIRTHINFO_DATE As String = ""
        Dim mCOUNTRY_DESC As String = ""
        Dim mDATASOURCE As String = ""
        Dim mSANC_UPDATE_DATE As String = ""



        Dim lvsCustType As Integer = Session("KYC")
        '''''''''''''''''''''''

        Try

            Dim DeletedQuery = (From m In KYCEntity.MCUST_SANC_LIST
                               Where m.CUSTSEQ = key _
                              Select m).ToList

            If DeletedQuery.Count > 0 Then
                For i As Integer = 0 To DeletedQuery.Count - 1
                    KYCEntity.MCUST_SANC_LIST.DeleteObject(DeletedQuery(i))
                Next i
            End If
            ''''''''''''''''''''''

            For Each lvsRow_No As GridViewRow In Me.grdList.Rows
                Dim newCust_Sanct As New MCUST_SANC_LIST

                ''''get values from Gridview '''''''

                Dim lvsCHKBOX = CType(lvsRow_No.FindControl("chkList"), CheckBox).Checked
                If lvsCHKBOX Then
                    chActive = "Y"
                Else
                    chActive = "N"
                End If


                mENTITY_ID = lvsRow_No.Cells(1).Text : If mENTITY_ID = "&nbsp;" Then mENTITY_ID = ""
                mFAM_UniqueID = lvsRow_No.Cells(2).Text : If mFAM_UniqueID = "&nbsp;" Then mFAM_UniqueID = ""
                mFIRSTNAME_E = lvsRow_No.Cells(3).Text : If mFIRSTNAME_E = "&nbsp;" Then mFIRSTNAME_E = ""
                mMIDDLE_NAME_E = lvsRow_No.Cells(4).Text : If mMIDDLE_NAME_E = "&nbsp;" Then mMIDDLE_NAME_E = ""
                mSURNAME_E = lvsRow_No.Cells(5).Text : If mSURNAME_E = "&nbsp;" Then mSURNAME_E = ""
                mFullName = lvsRow_No.Cells(6).Text : If mFullName = "&nbsp;" Then mFullName = ""
                mFIRST_NAME = lvsRow_No.Cells(7).Text : If mFIRST_NAME = "&nbsp;" Then mFIRST_NAME = ""
                mMID_NAME = lvsRow_No.Cells(8).Text : If mMID_NAME = "&nbsp;" Then mMID_NAME = ""
                mSURNAME = lvsRow_No.Cells(9).Text : If mSURNAME = "&nbsp;" Then mSURNAME = ""
                mORIGINAL_SCRIPT_NAME = lvsRow_No.Cells(10).Text : If mORIGINAL_SCRIPT_NAME = "&nbsp;" Then mORIGINAL_SCRIPT_NAME = ""
                mBIRTHINFO_DATE = lvsRow_No.Cells(11).Text : If mBIRTHINFO_DATE = "&nbsp;" Then mBIRTHINFO_DATE = ""
                mCOUNTRY_DESC = lvsRow_No.Cells(12).Text : If mCOUNTRY_DESC = "&nbsp;" Then mCOUNTRY_DESC = ""
                mDATASOURCE = lvsRow_No.Cells(13).Text : If mDATASOURCE = "&nbsp;" Then mDATASOURCE = ""

                ''''Use Findcontrol method
                Dim lbdate = CType(lvsRow_No.FindControl("lblActiveDate"), Label).Text
                mSANC_UPDATE_DATE = lbdate : If mSANC_UPDATE_DATE = "&nbsp;" Then mSANC_UPDATE_DATE = ""
                ''''''''''''''''''''''''''''''''''''

                '''''''LINQ Start here '''''''''''''
                newCust_Sanct.CUSTSEQ = key
                newCust_Sanct.CUSTTYPE = Session("KYC")
                newCust_Sanct.SEQ = lvsRow_No.RowIndex + 1
                newCust_Sanct.CHKLIST = chActive
                newCust_Sanct.UNIQUEID = mFAM_UniqueID.Trim
                newCust_Sanct.FIRSTNAME_E = mFIRSTNAME_E.Trim
                newCust_Sanct.MIDDLE_NAME_E = mMIDDLE_NAME_E.Trim
                newCust_Sanct.SURNAME_E = mSURNAME_E.Trim
                newCust_Sanct.FULLNAME = mFullName.Trim
                newCust_Sanct.FIRST_NAME = mFIRST_NAME.Trim
                newCust_Sanct.MIDDLE_NAME = mMID_NAME.Trim
                newCust_Sanct.SURNAME = mSURNAME.Trim
                newCust_Sanct.ORIGINAL_SCRIPT_NAME = mORIGINAL_SCRIPT_NAME.Trim
                newCust_Sanct.BIRTHINFO_DATE = mBIRTHINFO_DATE.Trim
                newCust_Sanct.COUNTRY_DESC = mCOUNTRY_DESC.Trim
                newCust_Sanct.DATASOURCE = mDATASOURCE.Trim
                newCust_Sanct.ENTITY_ID = mENTITY_ID.Trim
                newCust_Sanct.SANC_UPDATE_DATE = mSANC_UPDATE_DATE.Trim
                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                newCust_Sanct.CREATED_DATE = Now
                newCust_Sanct.CREATED_BY = clsSessionMenuRight.getUserName
                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                KYCEntity.AddToMCUST_SANC_LIST(newCust_Sanct)

            Next
            KYCEntity.SaveChanges()

        Catch ex As Exception
            Throw ex

        End Try



    End Sub

#End Region


#Region "BO"

    Sub Bind_Data_togrid_BO()

        '''' Connect Data to Grid '''''''''''
        Me.dtBo.Columns.Add("CIF_NO")
        Me.dtBo.Columns.Add("UNIQUEID")
        Me.dtBo.Columns.Add("PASSPORT_NO")

        Me.dtBo.Columns.Add("OTH_ID_TYPE")
        Me.dtBo.Columns.Add("OTH_ID_DESC")
        Me.dtBo.Columns.Add("OTH_ID_NO")

        Me.dtBo.Columns.Add("THPREFIX")
        Me.dtBo.Columns.Add("THPREFIX_DESC")
        Me.dtBo.Columns.Add("THFIRSTNAME")
        Me.dtBo.Columns.Add("THMIDNAME")
        Me.dtBo.Columns.Add("THLASTNAME")

        Me.dtBo.Columns.Add("ENPREFIX")
        Me.dtBo.Columns.Add("ENPREFIX_DESC")
        Me.dtBo.Columns.Add("ENFIRSTNAME")
        Me.dtBo.Columns.Add("ENMIDNAME")
        Me.dtBo.Columns.Add("ENLASTNAME")

        Me.dtBo.Columns.Add("ACC_OWN_RELATION")

        Me.dtBo.Columns.Add("FILTER_RESULT")
        Me.dtBo.Columns.Add("RISK_LEVEL")

        Me.dtBo.Columns.Add("ACTIVE")

        Dim lvsCustType As Integer = Session("KYC")

        Dim QryBO = (From tbName In KYCEntity.MCUST_BO
                        Where tbName.CUSTSEQ = CustSeq
                       Select tbName.SEQ,
                              tbName.CIF_NO,
                              tbName.UNIQUEID,
                              tbName.PASSPORT_NO,
                              tbName.OTH_ID_TYPE,
                              tbName.OTH_ID_DESC,
                              tbName.OTH_ID_NO,
                              tbName.THPREFIX,
                              tbName.THPREFIX_DESC,
                              tbName.THFIRSTNAME,
                              tbName.THMIDNAME,
                              tbName.THLASTNAME,
                              tbName.ENPREFIX,
                              tbName.ENPREFIX_DESC,
                              tbName.ENFIRSTNAME,
                              tbName.ENMIDNAME,
                              tbName.ENLASTNAME,
                              tbName.ACC_OWN_RELATION,
                              tbName.FILTER_RESULT,
                              tbName.RISK_LEVEL,
                              ACTIVE = If(tbName.ACTIVE = "Y", True, False)
                     Order By SEQ)

        For Each mRow In QryBO
            Me.dtBo.Rows.Add(mRow.CIF_NO,
                             mRow.UNIQUEID,
                             mRow.PASSPORT_NO,
                             mRow.OTH_ID_TYPE,
                             mRow.OTH_ID_DESC,
                             mRow.OTH_ID_NO,
                             mRow.THPREFIX,
                             mRow.THPREFIX_DESC,
                             mRow.THFIRSTNAME,
                             mRow.THMIDNAME,
                             mRow.THLASTNAME,
                             mRow.ENPREFIX,
                             mRow.ENPREFIX_DESC,
                             mRow.ENFIRSTNAME,
                             mRow.ENMIDNAME,
                             mRow.ENLASTNAME,
                             mRow.ACC_OWN_RELATION,
                             mRow.FILTER_RESULT,
                             mRow.RISK_LEVEL,
                             mRow.ACTIVE)

            Me.dtBo.AcceptChanges()
        Next

        Me.grdBo.DataSource = Me.dtBo
        Me.grdBo.DataBind()
        ''''Number of Rows '''''''''''''''''''''
        Me.lblCount_BO.Text = Me.dtBo.Rows.Count
        ''''''''''''''''''''''''''''''''''''''''
        Session("PopBo") = Me.dtBo

    End Sub

    Protected Sub chk_ACT_CUST_BO_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        ''''check Session ''''''''''''''''''''''
        If Not (Session("PopBO") Is Nothing) Then
            Me.dtBo = Session("PopBO")
        End If

        '''''' assign checkbox value to data table 
        For i = 0 To Me.grdBo.Rows.Count - 1
            Me.dtBo.Rows(i).Item("ACTIVE") = CType(Me.grdBo.Rows(i).Cells(10).FindControl("chk_ACT_CUST_BO"), CheckBox).Checked
        Next i

        Me.dtBo.AcceptChanges()
        Me.grdBo.DataSource = Me.dtBo
        Me.grdBo.DataBind()

        Session("PopBO") = Me.dtBo

    End Sub

    Protected Sub btAddBo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btAddBo.Click
        Add_To_grid_BO()
    End Sub

    Function Validate_Acct_BO() As Boolean

        clsCheckID = New clsCheckID

        Validate_Acct_BO = False


        If Me.txtBO_uniqueID.Text = "" And Me.txtBO_PASSPORT_NO.Text = "" Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('กรุณาป้อนเลขที่บัตรประชาขนหรือเลขที่หนังสือเดินทางให้ถูกต้อง');", True)
            txtBO_uniqueID.Focus()
            Exit Function
        ElseIf Me.txtBO_uniqueID.Text <> "" Then
            If Not (clsCheckID.chkIDcard(txtBO_uniqueID.Text.Trim)) Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('เลขที่บัตรประชาชนไม่ถูกต้อง');", True)
                Exit Function
                txtBO_uniqueID.Focus()
            End If
        ElseIf Me.txtBO_uniqueID.Text <> "" And Me.txtBO_PASSPORT_NO.Text <> "" Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('เลขที่บัตรประชาชนไม่ถูกต้อง');", True)
            Exit Function
            txtBO_uniqueID.Focus()
        End If

        ''''''''''''validate ข้อมูลซ้ำ''''''''''''
        Dim mBoIdCard As String = ""
        For Each rowNumber As GridViewRow In grdBo.Rows

            mBoIdCard = rowNumber.Cells(2).Text

            If mBoIdCard.Trim = Me.txtBO_uniqueID.Text.Trim Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ข้อมูลซ้ำ ! กรูณาป้อนเลขที่บัตรประชาชนใหม่');", True)
                txtBO_uniqueID.Focus()
                Exit Function
            End If

        Next
        ''''''''''''''''''''''''''''''''''''''

        If clsValid.CheckNull(Me.txtBO_FIRSTNAME_TH) = False Then Exit Function
        If clsValid.CheckNull(Me.txtBO_LASTNAME_TH) = False Then Exit Function
        If lblFILTER_RESULT_BO.Text = "" Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ต้องทำการตรวจกรองรายชือก่อน');", True)
            Exit Function
            lblFILTER_RESULT_BO.Focus()
        End If


        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        '''''หาว่าข้อมูลที่ป้อนมีชื่อไม่ตรงกับใน Mcustomer '''''''''''''''''''''''

        clsDatabase = New clsDatabase

        Dim dtSmartCard As DataTable = New DataTable
        Dim lvsSmartCard_FirstName As String = ""
        Dim lvsSmartCard_LastName As String = ""

        lvsSQL = ""
        lvsSQL += "      SELECT THFIRSTNAME,                                "
        lvsSQL += "             THMIDNAME,                                  "
        lvsSQL += "             THLASTNAME                                  "
        lvsSQL += "        FROM MCUSTOMER                                   "
        lvsSQL += "       WHERE UNIQUEID = '" & Me.txtBO_uniqueID.Text & "' "
        dtSmartCard = clsDatabase.QueryDataTable(lvsSQL)

        If (dtSmartCard.Rows.Count <> 0) Then

            If Not IsDBNull(dtSmartCard.Rows(0)("THFIRSTNAME")) Then lvsSmartCard_FirstName = dtSmartCard.Rows(0)("THFIRSTNAME")
            If Not IsDBNull(dtSmartCard.Rows(0)("THLASTNAME")) Then lvsSmartCard_LastName = dtSmartCard.Rows(0)("THLASTNAME")

            If lvsSmartCard_FirstName.Trim & lvsSmartCard_LastName.Trim _
                <> Me.txtBO_FIRSTNAME_TH.Text.Trim & Me.txtBO_LASTNAME_TH.Text.Trim Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                              "alertMessage",
                              "window.alert('เลขที่บัตรประชาชนที่ป้อนมี-ชื่อหรือนามสกุล-ไม่ตรงกับข้อมูลจากระบบ KYC');", True)
                Exit Function
                Me.txtBO_FIRSTNAME_TH.Focus()
            End If

        End If
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

        Validate_Acct_BO = True
    End Function

    Sub Add_To_grid_BO()

        If Me.Validate_Acct_BO = False Then Exit Sub

        'check session of data table
        If Not (Session("PopBo") Is Nothing) Then
            Me.dtBo = Session("PopBo")
        End If


        '''''''' insert data to grid row '''''''''''''''''''''''''''''''''''''''''''''''''
        Dim lvsddlType As String = ""
        Dim lvsddlDESC As String = ""
        If ddlOTH_ID_BO.SelectedIndex = -1 Then
            lvsddlType = ""
            lvsddlDESC = ""
        Else
            lvsddlType = ddlOTH_ID_BO.SelectedIndex
            lvsddlDESC = ddlOTH_ID_BO.SelectedItem.Text

        End If

        dtBo.Rows.Add(Me.txtBO_CIF_NO.Text,
                      Me.txtBO_uniqueID.Text,
                      Me.txtBO_PASSPORT_NO.Text,
                      lvsddlType,
                      lvsddlDESC,
                      Me.txtOTH_ID_NO_BO.Text,
                      Me.ddlPrefixTH_BO.SelectedIndex,
                      Me.ddlPrefixTH_BO.SelectedItem,
                      Me.txtBO_FIRSTNAME_TH.Text,
                      Me.txtBO_MIDNAME_TH.Text,
                      Me.txtBO_LASTNAME_TH.Text,
                      Me.ddlPrefixEN_BO.SelectedIndex,
                      Me.ddlPrefixEN_BO.SelectedItem,
                      Me.txtBO_FIRSTNAME_EN.Text,
                      Me.txtBO_MIDNAME_EN.Text,
                      Me.txtBO_LASTNAME_EN.Text,
                      Me.txtBO_ACC_OWN_RELATION.Text,
                      Me.lblFILTER_RESULT_BO.Text,
                      Me.lblRISK_LEVEL_BO.Text,
                      True)
        dtBo.AcceptChanges()
        Me.grdBo.DataSource = dtBo
        Me.grdBo.DataBind()
        ''''Number of Rows '''''''''''''''''''''
        Me.lblCount_BO.Text = Me.dtBo.Rows.Count
        ''''''''''''''''''''''''''''''''''''''''
        ''''deselect '''''''''''''''
        Me.grdBo.SelectedIndex = -1
        ''''''''''''''''''''''''''''
        'now bind datatable to gridview... 
        Session("PopBo") = Me.dtBo

        '''''Clear Screen '''''''''''''''
        Me.Clear_BO()
        Me.txtBO_uniqueID.Focus()

    End Sub

    Protected Sub btDelBo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btDelBo.Click
        Delete_grdRow_grdBO()
    End Sub

    Sub Delete_grdRow_grdBO()
        Try

            Dim index As Integer = grdBo.SelectedIndex
            If index = -1 Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "clientScript", "alert('ต้องเลือก BO ที่ต้องการลบก่อน')", True)
            Else

                'check session of data table
                If Not (Session("PopBo") Is Nothing) Then
                    Me.dtBo = Session("PopBo")
                End If
                ''''remove row at...
                dtBo.Rows.RemoveAt(index)
                dtBo.AcceptChanges()

                ''''bind data again
                grdBo.DataSource = dtBo
                grdBo.DataBind()
                ''''Number of Rows '''''''''''''''''''''
                Me.lblCount_BO.Text = Me.dtBo.Rows.Count
                ''''''''''''''''''''''''''''''''''''''''
                ''''deselect '''''''''''
                grdBo.SelectedIndex = -1
                '''''''''''''''''''''''''


            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Page,
                                                Page.GetType(),
                                                "clientScript",
                                                "alert('" + ex.Message.Replace("'", "") + "')",
                                                True)
        End Try
    End Sub

    Protected Sub grdBo_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdBo.SelectedIndexChanged
        If grdBo.SelectedIndex = intBeforeSelectIndex_BO Then
            grdBo.SelectedIndex = -1
        End If
    End Sub

    Protected Sub grdBo_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdBo.SelectedIndexChanging
        Me.intBeforeSelectIndex_BO = grdBo.SelectedIndex
    End Sub

    Protected Sub Save_to_Cust_BO(ByVal key As Integer)


        Dim mBO_Cif_No As String = ""
        Dim mBO_UniqueID As String = ""
        Dim mBO_PassportNo As String = ""

        Dim mBO_OTH_ID_TYPE As String = ""
        Dim mBO_OTH_ID_DESC As String = ""
        Dim mBO_OTH_ID_NO As String = ""

        Dim mBO_THPREFIX As String = ""
        Dim mBO_THPREFIX_Desc As String = ""
        Dim mBO_THFIRSTNAME As String = ""
        Dim mBO_THMIDNAME As String = ""
        Dim mBO_THLASTNAME As String = ""

        Dim mBO_ENPREFIX As String = ""
        Dim mBO_ENPREFIX_Desc As String = ""
        Dim mBO_ENFIRSTNAME As String = ""
        Dim mBO_ENMIDNAME As String = ""
        Dim mBO_ENLASTNAME As String = ""

        Dim mBO_Relation As String = ""

        Dim mBO_Filter_Result As String = ""
        Dim mBO_Risk_level As String = ""
        Dim chActive As String = ""

        Dim lvsCustType As Integer = Session("KYC")
        '''''''''''''''''''''''

        Try

            Dim DeletedQuery = (From m In KYCEntity.MCUST_BO
                               Where m.CUSTSEQ = key _
                              Select m).ToList

            If DeletedQuery.Count > 0 Then
                For i As Integer = 0 To DeletedQuery.Count - 1
                    KYCEntity.MCUST_BO.DeleteObject(DeletedQuery(i))
                Next i
            End If
            ''''''''''''''''''''''
            For Each lvsRow_No As GridViewRow In Me.grdBo.Rows
                Dim newCust_BO As New MCUST_BO

                ''''get values from Gridview '''''''

                mBO_Cif_No = lvsRow_No.Cells(1).Text : If mBO_Cif_No = "&nbsp;" Then mBO_Cif_No = ""
                mBO_UniqueID = lvsRow_No.Cells(2).Text : If mBO_UniqueID = "&nbsp;" Then mBO_UniqueID = ""
                mBO_PassportNo = lvsRow_No.Cells(3).Text : If mBO_PassportNo = "&nbsp;" Then mBO_PassportNo = ""

                mBO_OTH_ID_TYPE = lvsRow_No.Cells(4).Text : If mBO_OTH_ID_TYPE = "&nbsp;" Then mBO_OTH_ID_TYPE = ""
                mBO_OTH_ID_DESC = lvsRow_No.Cells(5).Text : If mBO_OTH_ID_DESC = "&nbsp;" Then mBO_OTH_ID_DESC = ""
                mBO_OTH_ID_NO = lvsRow_No.Cells(6).Text : If mBO_OTH_ID_NO = "&nbsp;" Then mBO_OTH_ID_NO = ""

                mBO_THPREFIX = lvsRow_No.Cells(7).Text : If mBO_THPREFIX = "&nbsp;" Then mBO_THPREFIX = ""
                mBO_THPREFIX_Desc = lvsRow_No.Cells(8).Text : If mBO_THPREFIX_Desc = "&nbsp;" Then mBO_THPREFIX_Desc = ""
                mBO_THFIRSTNAME = lvsRow_No.Cells(9).Text : If mBO_THFIRSTNAME = "&nbsp;" Then mBO_THFIRSTNAME = ""
                mBO_THMIDNAME = lvsRow_No.Cells(10).Text : If mBO_THMIDNAME = "&nbsp;" Then mBO_THMIDNAME = ""
                mBO_THLASTNAME = lvsRow_No.Cells(11).Text : If mBO_THLASTNAME = "&nbsp;" Then mBO_THLASTNAME = ""

                mBO_ENPREFIX = lvsRow_No.Cells(12).Text : If mBO_ENPREFIX = "&nbsp;" Then mBO_ENPREFIX = ""
                mBO_ENPREFIX_Desc = lvsRow_No.Cells(13).Text : If mBO_ENPREFIX_Desc = "&nbsp;" Then mBO_ENPREFIX_Desc = ""
                mBO_ENFIRSTNAME = lvsRow_No.Cells(14).Text : If mBO_ENFIRSTNAME = "&nbsp;" Then mBO_ENFIRSTNAME = ""
                mBO_ENMIDNAME = lvsRow_No.Cells(15).Text : If mBO_ENMIDNAME = "&nbsp;" Then mBO_ENMIDNAME = ""
                mBO_ENLASTNAME = lvsRow_No.Cells(16).Text : If mBO_ENLASTNAME = "&nbsp;" Then mBO_ENLASTNAME = ""

                mBO_Relation = lvsRow_No.Cells(17).Text : If mBO_Relation = "&nbsp;" Then mBO_Relation = ""

                mBO_Filter_Result = lvsRow_No.Cells(18).Text : If mBO_Filter_Result = "&nbsp;" Then mBO_Filter_Result = ""
                mBO_Risk_level = lvsRow_No.Cells(19).Text : If mBO_Risk_level = "&nbsp;" Then mBO_Risk_level = "1"

                If (CType(lvsRow_No.Cells(20).FindControl("chk_ACT_CUST_BO"), CheckBox).Checked = True) Then
                    chActive = "Y"
                Else
                    chActive = "N"
                End If

                ''''''''''''''''''''''''''''''''''''

                '''''''LINQ Start here '''''''''''''
                newCust_BO.CUSTSEQ = key
                newCust_BO.CUSTTYPE = Session("KYC")
                newCust_BO.SEQ = lvsRow_No.RowIndex + 1
                newCust_BO.CIF_NO = mBO_Cif_No.Trim
                newCust_BO.UNIQUEID = mBO_UniqueID.Trim
                newCust_BO.PASSPORT_NO = mBO_PassportNo.Trim

                newCust_BO.OTH_ID_TYPE = mBO_OTH_ID_TYPE.Trim
                newCust_BO.OTH_ID_DESC = mBO_OTH_ID_DESC.Trim
                newCust_BO.OTH_ID_NO = mBO_OTH_ID_NO.Trim

                newCust_BO.THPREFIX = mBO_THPREFIX.Trim
                newCust_BO.THPREFIX_DESC = mBO_THPREFIX_Desc.Trim
                newCust_BO.THFIRSTNAME = mBO_THFIRSTNAME.Trim
                newCust_BO.THMIDNAME = mBO_THMIDNAME.Trim
                newCust_BO.THLASTNAME = mBO_THLASTNAME.Trim

                newCust_BO.ENPREFIX = mBO_ENPREFIX.Trim
                newCust_BO.ENPREFIX_DESC = mBO_ENPREFIX_Desc.Trim
                newCust_BO.ENFIRSTNAME = mBO_ENFIRSTNAME.Trim
                newCust_BO.ENMIDNAME = mBO_ENMIDNAME.Trim
                newCust_BO.ENLASTNAME = mBO_ENLASTNAME.Trim

                newCust_BO.ACC_OWN_RELATION = mBO_Relation.Trim

                newCust_BO.FILTER_RESULT = mBO_Filter_Result.Trim
                newCust_BO.RISK_LEVEL = mBO_Risk_level

                newCust_BO.ACTIVE = chActive
                newCust_BO.CREATED_DATE = Now
                newCust_BO.CREATED_BY = clsSessionMenuRight.getUserName
                KYCEntity.AddToMCUST_BO(newCust_BO)

            Next
            KYCEntity.SaveChanges()

        Catch ex As Exception
            Throw ex

        End Try


    End Sub

    Protected Sub Save_BO_ID_To_Mcustomer()

        Dim dtSmartCard As DataTable = New DataTable
        Dim CustSeq_BO As Integer = 0
        Dim mBO_Cif_No As String = ""
        Dim mBO_UniqueID As String = ""

        Dim mBO_THPREFIX As String = ""
        Dim mBO_THFIRSTNAME As String = ""
        Dim mBO_THMIDNAME As String = ""
        Dim mBO_THLASTNAME As String = ""

        Dim mBO_ENPREFIX As String = ""
        Dim mBO_ENFIRSTNAME As String = ""
        Dim mBO_ENMIDNAME As String = ""
        Dim mBO_ENLASTNAME As String = ""

        Dim mBO_Filter_Result As String = ""
        Dim mBO_Risk_Level As String = ""
        Dim mBO_Relation As String = ""
        Dim chActive As String = ""
        Dim lvsCustType As Integer = Session("KYC")
        '''''''''''''''''''''''
        Try

            ''''''''''''''''''''''
            For Each lvsRow_No As GridViewRow In Me.grdBo.Rows
                Dim newCustomer As New MCUSTOMER

                ''''get values from Gridview '''''''
                mBO_UniqueID = lvsRow_No.Cells(2).Text : If mBO_UniqueID = "&nbsp;" Then mBO_UniqueID = ""
                mBO_THPREFIX = lvsRow_No.Cells(7).Text : If mBO_THPREFIX = "&nbsp;" Then mBO_THPREFIX = ""
                mBO_THFIRSTNAME = lvsRow_No.Cells(9).Text : If mBO_THFIRSTNAME = "&nbsp;" Then mBO_THFIRSTNAME = ""
                mBO_THMIDNAME = lvsRow_No.Cells(10).Text : If mBO_THMIDNAME = "&nbsp;" Then mBO_THMIDNAME = ""
                mBO_THLASTNAME = lvsRow_No.Cells(11).Text : If mBO_THLASTNAME = "&nbsp;" Then mBO_THLASTNAME = ""

                mBO_ENPREFIX = lvsRow_No.Cells(12).Text : If mBO_ENPREFIX = "&nbsp;" Then mBO_ENPREFIX = ""
                mBO_ENFIRSTNAME = lvsRow_No.Cells(14).Text : If mBO_ENFIRSTNAME = "&nbsp;" Then mBO_ENFIRSTNAME = ""
                mBO_ENMIDNAME = lvsRow_No.Cells(15).Text : If mBO_ENMIDNAME = "&nbsp;" Then mBO_ENMIDNAME = ""
                mBO_ENLASTNAME = lvsRow_No.Cells(16).Text : If mBO_ENLASTNAME = "&nbsp;" Then mBO_ENLASTNAME = ""

                mBO_Filter_Result = lvsRow_No.Cells(18).Text : If mBO_Filter_Result = "&nbsp;" Then mBO_Filter_Result = ""
                mBO_Risk_Level = lvsRow_No.Cells(19).Text : If mBO_Risk_Level = "&nbsp;" Then mBO_Risk_Level = ""


                lvsSQL = ""
                lvsSQL += "      SELECT THFIRSTNAME,                        "
                lvsSQL += "             THMIDNAME,                          "
                lvsSQL += "             THLASTNAME                          "
                lvsSQL += "        FROM MCUSTOMER                           "
                lvsSQL += "       WHERE UNIQUEID = '" & mBO_UniqueID & "'   "
                dtSmartCard = clsDatabase.QueryDataTable(lvsSQL)

                If (dtSmartCard.Rows.Count = 0) Then

                    Dim lvsrow As Integer
                    lvsrow += 1
                    CustSeq_BO = Gen_CusSeq(CInt(lvsrow))

                    '''''''LINQ Start here '''''''''''''
                    newCustomer.CUSTSEQ = CustSeq_BO
                    newCustomer.CUSTTYPE = lvsCustType
                    newCustomer.UNIQUEID = mBO_UniqueID.Trim

                    newCustomer.THPREFIX = mBO_THPREFIX.Trim
                    newCustomer.THFIRSTNAME = mBO_THFIRSTNAME.Trim
                    newCustomer.THMIDNAME = mBO_THMIDNAME.Trim
                    newCustomer.THLASTNAME = mBO_THLASTNAME.Trim

                    newCustomer.ENPREFIX = mBO_ENPREFIX.Trim
                    newCustomer.ENFIRSTNAME = mBO_ENFIRSTNAME.Trim
                    newCustomer.ENMIDNAME = mBO_ENMIDNAME.Trim
                    newCustomer.ENLASTNAME = mBO_ENLASTNAME.Trim
                    newCustomer.FILTER_RESULT = mBO_Filter_Result.Trim
                    newCustomer.RISK_LEVEL = mBO_Risk_Level.Trim
                    newCustomer.AMLCDD = mBO_Risk_Level.Trim

                    newCustomer.TRANTYPE = "2" '''''เป็น BO
                    newCustomer.UPDATEDATE = Now.ToShortDateString
                    newCustomer.UPDATEBY = clsSessionMenuRight.getUserName
                    newCustomer.BRANCHCODE = clsSessionMenuRight.getBranchCode
                    newCustomer.ZONECODE = clsSessionMenuRight.getZoneCode
                    newCustomer.DEPTCODE = clsSessionMenuRight.getDeptCode
                    newCustomer.ALLCODERIGHT = clsSessionMenuRight.getAllCodeRight
                    newCustomer.CREATEBY = clsSessionMenuRight.getUserName
                    newCustomer.CREATEDATE = Now.ToShortDateString
                    KYCEntity.AddToMCUSTOMER(newCustomer)

                End If

                ''''''''''''''''''''''''''''''''''''
            Next
            KYCEntity.SaveChanges()

        Catch ex As Exception
            Throw ex

        End Try


    End Sub

    Sub Clear_BO()

        Me.txtBO_CIF_NO.Text = ""
        Me.txtBO_uniqueID.Text = ""
        Me.txtBO_PASSPORT_NO.Text = ""

        Me.ddlPrefixTH_BO.SelectedIndex = -1
        Me.txtBO_FIRSTNAME_TH.Text = ""
        Me.txtBO_MIDNAME_TH.Text = ""
        Me.txtBO_LASTNAME_TH.Text = ""

        Me.ddlPrefixEN_BO.SelectedIndex = -1
        Me.txtBO_FIRSTNAME_EN.Text = ""
        Me.txtBO_MIDNAME_EN.Text = ""
        Me.txtBO_LASTNAME_EN.Text = ""

        Me.txtBO_ACC_OWN_RELATION.Text = ""

        Me.lblFILTER_RESULT_BO.Text = ""
        Me.lblRISK_LEVEL_BO.Text = ""

    End Sub


    Sub Find_Mcustomer_for_BO(ByVal Citizen_ID As String)

        Try

            If Me.Validate_ID_CARD(Me.txtBO_uniqueID) = False Then Exit Sub

            Dim dtSmartCard As DataTable = New DataTable

            Me.txtBO_FIRSTNAME_TH.Text = ""
            Me.txtBO_MIDNAME_TH.Text = ""
            Me.txtBO_LASTNAME_TH.Text = ""

            Me.txtBO_FIRSTNAME_EN.Text = ""
            Me.txtBO_MIDNAME_EN.Text = ""
            Me.txtBO_LASTNAME_EN.Text = ""

            lvsSQL = ""
            lvsSQL += "      SELECT THFIRSTNAME,                        "
            lvsSQL += "             THMIDNAME,                          "
            lvsSQL += "             THLASTNAME,                         "
            lvsSQL += "             THPREFIX,                           "
            lvsSQL += "             ENFIRSTNAME,                        "
            lvsSQL += "             ENMIDNAME,                          "
            lvsSQL += "             ENLASTNAME,                         "
            lvsSQL += "             ENPREFIX                            "
            lvsSQL += "        FROM MCUSTOMER                           "
            lvsSQL += "       WHERE UNIQUEID = '" & Citizen_ID & "'     "
            dtSmartCard = clsDatabase.QueryDataTable(lvsSQL)

            If (dtSmartCard.Rows.Count <> 0) Then
                If Not IsDBNull(dtSmartCard.Rows(0)("THPREFIX")) Then Me.ddlPrefixTH_BO.SelectedValue = dtSmartCard.Rows(0)("THPREFIX")
                If Not IsDBNull(dtSmartCard.Rows(0)("THFIRSTNAME")) Then Me.txtBO_FIRSTNAME_TH.Text = dtSmartCard.Rows(0)("THFIRSTNAME")
                If Not IsDBNull(dtSmartCard.Rows(0)("THMIDNAME")) Then Me.txtBO_MIDNAME_TH.Text = dtSmartCard.Rows(0)("THMIDNAME")
                If Not IsDBNull(dtSmartCard.Rows(0)("THLASTNAME")) Then Me.txtBO_LASTNAME_TH.Text = dtSmartCard.Rows(0)("THLASTNAME")

                If Not IsDBNull(dtSmartCard.Rows(0)("ENPREFIX")) Then Me.ddlPrefixEN_BO.SelectedValue = dtSmartCard.Rows(0)("ENPREFIX")
                If Not IsDBNull(dtSmartCard.Rows(0)("ENFIRSTNAME")) Then Me.txtBO_FIRSTNAME_EN.Text = dtSmartCard.Rows(0)("ENFIRSTNAME")
                If Not IsDBNull(dtSmartCard.Rows(0)("ENMIDNAME")) Then Me.txtBO_MIDNAME_EN.Text = dtSmartCard.Rows(0)("ENMIDNAME")
                If Not IsDBNull(dtSmartCard.Rows(0)("ENLASTNAME")) Then Me.txtBO_LASTNAME_EN.Text = dtSmartCard.Rows(0)("ENLASTNAME")

                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ระบบได้ชื่อและนามสกุลจากระบบ KYC มาแสดง');", True)
            Else
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ไม่พบข้อมูลจากระบบ KYC ระบบจะค้นหาข้อมููลจากระบบ Smart Card');", True)
                Me.Find_SmartCard_for_BO(Me.txtBO_uniqueID.Text)
            End If


        Catch ex As Exception
            '  Console.WriteLine("")
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                                    "clientScript",
                                    "alert('" + ex.Message.Replace("'", "") + "')",
                                    True)

        End Try

    End Sub


    Function Validate_ID_CARD() As Boolean

        clsCheckID = New clsCheckID

        Validate_ID_CARD = False

        If clsValid.CheckNull(Me.txtBO_uniqueID) = False Then Exit Function

        If Len(Me.txtBO_uniqueID.Text) <> 13 Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('เลขที่บัตรประชาชนไม่ครบ 13 หลัก');", True)
            Exit Function
            Me.txtBO_uniqueID.Focus()
        End If

        If clsValid.CheckNumeric_Smartcard(Me.txtBO_uniqueID) = False Then Exit Function


        If Not (clsCheckID.chkIDcard(txtBO_uniqueID.Text.Trim)) Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('เลขที่บัตรประชาชนไม่ถูกต้อง');", True)
            Exit Function
            txtBO_uniqueID.Focus()
        End If


        Validate_ID_CARD = True
    End Function

    Protected Sub btnSearch_BO_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch_BO.Click
        Me.Find_Mcustomer_for_BO(Me.txtBO_uniqueID.Text)
    End Sub

    Protected Sub btnClear_BO_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear_BO.Click
        Me.Clear_BO() : Me.txtBO_uniqueID.Focus()
    End Sub

    Sub Find_SmartCard_for_BO(ByVal Citizen_ID As String)

        Try

            If Me.Validate_ID_CARD(Me.txtBO_uniqueID) = False Then Exit Sub


            Dim dtSmartCard As DataTable = New DataTable

            lvsSQL = ""
            lvsSQL += "     SELECT FIRST_NAME,                          "
            lvsSQL += "            LAST_NAME,                           "
            lvsSQL += "            FIRST_NAME_EN,                       "
            lvsSQL += "            LAST_NAME_EN,                        "
            lvsSQL += "            BIRTH_DATE,                          "
            lvsSQL += "            START_DATE                           "
            lvsSQL += "       FROM KYCADMIN.GHB_BORAINTERFACE           "
            lvsSQL += "      WHERE CITIZEN_ID = '" & Citizen_ID & "'    "
            dtSmartCard = clsDatabase.QueryDataTable(lvsSQL)

            If (dtSmartCard.Rows.Count <> 0) Then

                If Not IsDBNull(dtSmartCard.Rows(0)("FIRST_NAME")) Then Me.txtBO_FIRSTNAME_TH.Text = dtSmartCard.Rows(0)("FIRST_NAME")
                If Not IsDBNull(dtSmartCard.Rows(0)("LAST_NAME")) Then Me.txtBO_LASTNAME_TH.Text = dtSmartCard.Rows(0)("LAST_NAME")

                If Not IsDBNull(dtSmartCard.Rows(0)("FIRST_NAME_EN")) Then Me.txtBO_FIRSTNAME_EN.Text = dtSmartCard.Rows(0)("FIRST_NAME_EN")
                If Not IsDBNull(dtSmartCard.Rows(0)("LAST_NAME_EN")) Then Me.txtBO_LASTNAME_EN.Text = dtSmartCard.Rows(0)("LAST_NAME_EN")

                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ระบบได้ชื่อและนามสกุลจากระบบ Smart Card มาแสดง');", True)
            Else
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ไม่พบข้อมูลจาก Smart Card');", True)
                Me.ddlPrefixTH_BO.Focus()
            End If


        Catch ex As Exception
            '  Console.WriteLine("")
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                                    "clientScript",
                                    "alert('" + ex.Message.Replace("'", "") + "')",
                                    True)

        End Try

    End Sub

    Function Validate_ID_CARD(ByVal Unique_no As Object) As Boolean

        clsCheckID = New clsCheckID

        Validate_ID_CARD = False

        If clsValid.CheckNull(Unique_no) = False Then Exit Function

        If Len(Unique_no.Text) <> 13 Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('เลขที่บัตรประชาชนไม่ครบ 13 หลัก');", True)
            Exit Function
            Unique_no.Focus()
        End If

        '  If clsValid.CheckNumeric_Smartcard(Unique_no) = False Then Exit Function


        If Not (clsCheckID.chkIDcard(Unique_no.text)) Then
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('เลขที่บัตรประชาชนไม่ถูกต้อง');", True)
            Exit Function
            Unique_no.Focus()
        End If


        Validate_ID_CARD = True
    End Function

#End Region

     Protected Sub btnFilter_BO_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter_BO.Click
        Try
            Session("chkKYC") = Nothing
            Dim lvsWhatIsThis As DataSet = Session("ds")
            If Not lvsWhatIsThis Is Nothing AndAlso lvsWhatIsThis.Tables("Result").Rows.Count > 0 Then
                lblRISK_LEVEL_BO.Text = Me.hdfLevel.Value
                '''''''''''''''''''''''''''''''''''''''''''
                grdList.DataSource = lvsWhatIsThis.Tables("Result")
                grdList.DataBind()
                '''''''''''''''''''''''''''''''''''''''''''
            Else
                lblRISK_LEVEL_BO.Text = 0
            End If

            If Session("Sanction") = Nothing Then
                Me.lblFILTER_RESULT_BO.Text = "ไม่มีรายชื่อใน List"
                lblRISK_LEVEL_BO.Text = 1
            Else
                Me.lblFILTER_RESULT_BO.Text = "มีรายชื่อใน List"
            End If

            Session("Sanction") = Nothing

        Catch ex As Exception
            Console.WriteLine("")

        End Try
    End Sub

    Protected Sub ddlFormalProvice_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlFormalProvince.SelectedIndexChanged
        Dim clsDropDown As New clsMasterDropDown

        If Not ddlFormalProvince.SelectedIndex = 0 Then
            clsDropDown.setAmphor(ddlFormalAmphor, ProviceCode:=ddlFormalProvince.SelectedValue)
        Else
            ddlFormalAmphor.Items.Clear()
            Me.ddlFormalTambol.Items.Clear()
        End If
    End Sub

    Protected Sub ddlFormalAmphor_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlFormalAmphor.SelectedIndexChanged
        Dim clsDropDown As New clsMasterDropDown

        If Not ddlFormalAmphor.SelectedIndex = 0 Then
            clsDropDown.setTambol(ddlFormalTambol, AmphorCode:=ddlFormalAmphor.SelectedValue)
        Else
            ddlFormalTambol.Items.Clear()
        End If
    End Sub

    Protected Sub ddlWORKProvice_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlWORKPROVINCE.SelectedIndexChanged
        Dim clsDropDown As New clsMasterDropDown

        If Not ddlWORKPROVINCE.SelectedIndex = 0 Then
            clsDropDown.setAmphor(ddlWORKAMPHOR, ProviceCode:=ddlWORKPROVINCE.SelectedValue)
        Else
            ddlWORKAMPHOR.Items.Clear()
            Me.ddlWORKTAMBOL.Items.Clear()
        End If
    End Sub

    Protected Sub ddlWORKAmphor_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlWORKAMPHOR.SelectedIndexChanged
        Dim clsDropDown As New clsMasterDropDown

        If Not ddlWORKAMPHOR.SelectedIndex = 0 Then
            clsDropDown.setTambol(ddlWORKTAMBOL, AmphorCode:=ddlWORKAMPHOR.SelectedValue)
        Else
            ddlWORKTAMBOL.Items.Clear()
        End If
    End Sub

    Protected Sub btnFilter_Customer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter_CUST.Click
        Try
            Session("chkKYC") = Nothing
            Dim lvsWhatIsThis As DataSet = Session("ds")
            If Not lvsWhatIsThis Is Nothing AndAlso lvsWhatIsThis.Tables("Result").Rows.Count > 0 Then
                lblRISK_LEVEL_CUST.Text = Me.hdfLevel.Value
                '''''''''''''''''''''''''''''''''''''''''''
                grdList.DataSource = lvsWhatIsThis.Tables("Result")
                grdList.DataBind()
                '''''''''''''''''''''''''''''''''''''''''''
            Else
                lblRISK_LEVEL_CUST.Text = 0
            End If

            If Session("Sanction") = Nothing Then
                Me.lblFILTER_RESULT_CUST.Text = "ไม่มีรายชื่อใน List"
                lblRISK_LEVEL_CUST.Text = 1
            Else
                Me.lblFILTER_RESULT_CUST.Text = "มีรายชื่อใน List"
            End If


            Session("Sanction") = Nothing


        Catch ex As Exception
            Console.WriteLine("")

        End Try
    End Sub

#Region "Sanction"
    Sub Bind_Data_togrid_Sanction()


        '''' Connect Data to Grid '''''''''''
        Me.dtSanc.Columns.Add("SELECTLIST")
        Me.dtSanc.Columns.Add("ENTITY_ID")
        Me.dtSanc.Columns.Add("UNIQUEID")

        Me.dtSanc.Columns.Add("FIRST_NAME")
        Me.dtSanc.Columns.Add("MIDDLE_NAME")
        Me.dtSanc.Columns.Add("SURNAME")
        Me.dtSanc.Columns.Add("FULLNAME")

        Me.dtSanc.Columns.Add("FIRSTNAME_E")
        Me.dtSanc.Columns.Add("MIDDLE_NAME_E")
        Me.dtSanc.Columns.Add("SURNAME_E")
        Me.dtSanc.Columns.Add("ORIGINAL_SCRIPT_NAME")

        Me.dtSanc.Columns.Add("BIRTHINFO_DATE")
        Me.dtSanc.Columns.Add("DATASOURCE")
        Me.dtSanc.Columns.Add("COUNTRY_DESC")
        Me.dtSanc.Columns.Add("LastUpdateDate")

        Dim lvsCustType As Integer = Session("KYC")

        Dim QrySanct = (From tbName In KYCEntity.MCUST_SANC_LIST
                        Where tbName.CUSTSEQ = CustSeq
                       Select tbName.SEQ,
                              tbName.CHKLIST,
                              tbName.ENTITY_ID,
                              tbName.UNIQUEID,
                              tbName.FIRST_NAME,
                              tbName.MIDDLE_NAME,
                              tbName.SURNAME,
                              tbName.FIRSTNAME_E,
                              tbName.MIDDLE_NAME_E,
                              tbName.SURNAME_E,
                              tbName.FULLNAME,
                              tbName.DATASOURCE,
                              tbName.ORIGINAL_SCRIPT_NAME,
                              tbName.COUNTRY_DESC,
                              tbName.BIRTHINFO_DATE,
                              LastUpdateDate = tbName.SANC_UPDATE_DATE,
                              SELECTLIST = If(tbName.CHKLIST = "Y", True, False)
                     Order By SEQ)

        For Each mRow In QrySanct
            Me.dtSanc.Rows.Add(mRow.SELECTLIST,
                               mRow.ENTITY_ID,
                               mRow.UNIQUEID,
                               mRow.FIRST_NAME,
                               mRow.MIDDLE_NAME,
                               mRow.SURNAME,
                               mRow.FULLNAME,
                               mRow.FIRSTNAME_E,
                               mRow.MIDDLE_NAME_E,
                               mRow.SURNAME_E,
                               mRow.ORIGINAL_SCRIPT_NAME,
                               mRow.BIRTHINFO_DATE,
                               mRow.DATASOURCE,
                               mRow.COUNTRY_DESC,
                               mRow.LastUpdateDate)

            Me.dtSanc.AcceptChanges()
        Next

        Me.grdList.DataSource = Me.dtSanc
        Me.grdList.DataBind()
        ''''Number of Rows '''''''''''''''''''''
        Me.lblCount_Sanct.Text = Me.dtSanc.Rows.Count
        ''''''''''''''''''''''''''''''''''''''''
        Session("PopSanc") = Me.dtSanc

    End Sub

#End Region

#Region "แหล่งที่มาของรายได้"

    Sub Bind_Data_togrid_Income_Source()

        '''' Connect Data to Grid '''''''''''
        Me.dtIncome.Columns.Add("COUNTYNAME")
        Me.dtIncome.Columns.Add("NATIONCODE")
        Me.dtIncome.Columns.Add("COUNTYNAMETH")
        Me.dtIncome.Columns.Add("RISK_LEVEL")
        Me.dtIncome.Columns.Add("ACTIVE")

        Dim lvsCustType As Integer = Session("KYC")

        Dim QryIncome = (From tbName In KYCEntity.MCUST_INCOME_SOURCE
                        Where tbName.CUSTSEQ = CustSeq
                       Select tbName.SEQ,
                              tbName.COUNTYNAME,
                              tbName.NATIONCODE,
                              tbName.COUNTYNAMETH,
                              tbName.RISK_LEVEL,
                              ACTIVE = If(tbName.ACTIVE = "Y", True, False)
                     Order By SEQ)

        For Each mRow In QryIncome
            Me.dtIncome.Rows.Add(mRow.COUNTYNAME,
                                 mRow.NATIONCODE,
                                 mRow.COUNTYNAMETH,
                                 mRow.RISK_LEVEL,
                                 mRow.ACTIVE)

            Me.dtIncome.AcceptChanges()
        Next

        Me.grdIncome.DataSource = Me.dtIncome
        Me.grdIncome.DataBind()
        ''''Number of Rows ''''''''''''''''''''''''''''''''''
        Me.lblCount_Inc_Source.Text = Me.dtIncome.Rows.Count
        '''''''''''''''''''''''''''''''''''''''''''''''''''''
        Session("PopINCOME") = Me.dtIncome

    End Sub

    Protected Sub chk_ACT_INC_SOURCE_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        ''''check Session ''''''''''''''''''''''
        If Not (Session("PopINCOME") Is Nothing) Then
            Me.dtIncome = Session("PopINCOME")
        End If

        '''''' assign checkbox value to data table 
        For i = 0 To Me.grdIncome.Rows.Count - 1
            Me.dtIncome.Rows(i).Item("ACTIVE") = CType(Me.grdIncome.Rows(i).Cells(3).FindControl("chk_ACT_INC_SOURCE"), CheckBox).Checked
        Next i

        Me.dtIncome.AcceptChanges()
        Me.grdIncome.DataSource = Me.dtIncome
        Me.grdIncome.DataBind()

        Session("PopINCOME") = Me.dtIncome

    End Sub

    Function Validate_Income() As Boolean
        Validate_Income = False

        ''''''''Validate ข้อมูลซ้ำ''''''''''''''''''
        Dim mIncome As String = ""
        For Each rowIncome As GridViewRow In grdIncome.Rows
            mIncome = rowIncome.Cells(1).Text
            If mIncome = ddlIncomeSource1.SelectedItem.Text Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ข้อมูลซ้ำ ! กรูณาเลือกแหล่งที่มาของรายได้อื่น');", True)
                ddlIncomeSource1.Focus()
                Exit Function
            End If

        Next
        '''''''''''''''''''''''''''''
        Validate_Income = True
    End Function

    Protected Sub btAddIncome_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btAddIncome.Click
        Me.Add_To_grid_Inc_Source()
    End Sub

    Sub Add_To_grid_Inc_Source()

        If Validate_Income() = False Then Exit Sub

        'check session of data table
        If Not (Session("PopINCOME") Is Nothing) Then
            Me.dtIncome = Session("PopINCOME")
        End If

        '''''''''''''


        '''''''''
        Dim dtMNAT As DataTable = New DataTable
        Dim lvsNationNameThai As String = ""
        Dim lvsRisk As Integer = 0

        lvsSQL = ""
        lvsSQL += "     SELECT COUNTYNAMETHAI, RISK                                     "
        lvsSQL += "       FROM KYCADMIN.MNATIONALITY                                    "
        lvsSQL += "      WHERE NATIONCODE = '" & Me.ddlIncomeSource1.SelectedValue & "' "
        dtMNAT = clsDatabase.QueryDataTable(lvsSQL)

        If (dtMNAT.Rows.Count <> 0) Then
            If Not IsDBNull(dtMNAT.Rows(0)("COUNTYNAMETHAI")) Then lvsNationNameThai = dtMNAT.Rows(0)("COUNTYNAMETHAI")
            If Not IsDBNull(dtMNAT.Rows(0)("RISK")) Then lvsRisk = dtMNAT.Rows(0)("RISK")
        End If
        ''''''''''

        '''''''' insert data to grid row '''''''''''''''''''''''''''''''''''''''''''''''''
        dtIncome.Rows.Add(Me.ddlIncomeSource1.SelectedItem,
                          Me.ddlIncomeSource1.SelectedValue,
                          lvsNationNameThai,
                          lvsRisk,
                          True)
        dtIncome.AcceptChanges()
        Me.grdIncome.DataSource = dtIncome
        Me.grdIncome.DataBind()
        ''''Number of Rows ''''''''''''''''''''''''''''''''''
        Me.lblCount_Inc_Source.Text = Me.dtIncome.Rows.Count
        '''''''''''''''''''''''''''''''''''''''''''''''''''''
        ''''deselect ''''''''''''''''''''' 
        Me.grdIncome.SelectedIndex = -1
        ''''''''''''''''''''''''''''''''''
        '''''now bind datatable to gridview... 
        Session("PopINCOME") = Me.dtIncome

        ''''Clear Screen'''''''''
        Me.ddlIncomeSource1.Focus()
    End Sub

    Protected Sub btDelIncome_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btDelIncome.Click
        Delete_gridRow_grdIncome()
    End Sub

    Sub Delete_gridRow_grdIncome()
        Try

            Dim index As Integer = grdIncome.SelectedIndex
            If index = -1 Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "clientScript", "alert('ต้องเลือกแหล่งที่มาของรายได้ที่ต้องการลบก่อน')", True)
            Else
                'check session of data table
                If Not (Session("PopINCOME") Is Nothing) Then
                    Me.dtIncome = Session("PopINCOME")
                End If
                ''''remove row at...
                dtIncome.Rows.RemoveAt(index)
                dtIncome.AcceptChanges()

                ''''bind data again
                grdIncome.DataSource = Me.dtIncome
                grdIncome.DataBind()
                ''''Number of Rows ''''''''''''''''''''''''''''''''''
                Me.lblCount_Inc_Source.Text = Me.dtIncome.Rows.Count
                '''''''''''''''''''''''''''''''''''''''''''''''''''''

                ''''deselect ''''''''''''''''
                grdIncome.SelectedIndex = -1
                '''''''''''''''''''''''''''''
            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Page,
                                                Page.GetType(),
                                                "clientScript",
                                                "alert('" + ex.Message.Replace("'", "") + "')",
                                                True)
        End Try

    End Sub

    Protected Sub grdIncome_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdIncome.SelectedIndexChanged
        If grdIncome.SelectedIndex = intBeforeSelectIndex_Income Then
            grdIncome.SelectedIndex = -1
        End If
    End Sub

    Protected Sub grdIncome_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdIncome.SelectedIndexChanging
        Me.intBeforeSelectIndex_Income = grdIncome.SelectedIndex
    End Sub

    Protected Sub Save_to_Cust_Income_source(ByVal key As Integer)

        Dim mCountryName As String = ""
        Dim mNationCode As String = ""
        Dim mCountryNameTH As String = ""
        Dim mINC_RISK As String = ""
        Dim chActive As String = ""
        Dim lvsCustType As Integer = Session("KYC")
        '''''''''''''''''''''''

        Try

            Dim DeletedQuery = (From m In KYCEntity.MCUST_INCOME_SOURCE
                               Where m.CUSTSEQ = key _
                              Select m).ToList

            If DeletedQuery.Count > 0 Then
                For i As Integer = 0 To DeletedQuery.Count - 1
                    KYCEntity.MCUST_INCOME_SOURCE.DeleteObject(DeletedQuery(i))
                Next i
            End If
            ''''''''''''''''''''''
            For Each rowIncome As GridViewRow In Me.grdIncome.Rows
                Dim newCust_Income_Source As New MCUST_INCOME_SOURCE

                ''''get values from Gridview '''''''
                mCountryName = rowIncome.Cells(1).Text : If mCountryName = "&nbsp;" Then mCountryName = ""
                mNationCode = rowIncome.Cells(2).Text : If mNationCode = "&nbsp;" Then mNationCode = ""
                mCountryNameTH = rowIncome.Cells(3).Text : If mCountryNameTH = "&nbsp;" Then mCountryNameTH = ""

                mINC_RISK = rowIncome.Cells(4).Text : If mINC_RISK = "&nbsp;" Then mINC_RISK = 0
                If (CType(rowIncome.Cells(5).FindControl("chk_ACT_INC_SOURCE"), CheckBox).Checked = True) Then
                    chActive = "Y"
                Else
                    chActive = "N"
                End If

                ''''''''''''''''''''''''''''''''''''

                '''''''LINQ Start here ''''''''''''''
                newCust_Income_Source.CUSTSEQ = key
                newCust_Income_Source.CUSTTYPE = Session("KYC")
                newCust_Income_Source.SEQ = rowIncome.RowIndex + 1
                newCust_Income_Source.NATIONCODE = mNationCode
                newCust_Income_Source.COUNTYNAME = mCountryName
                newCust_Income_Source.COUNTYNAMETH = mCountryNameTH
                newCust_Income_Source.RISK_LEVEL = mINC_RISK
                newCust_Income_Source.ACTIVE = chActive
                newCust_Income_Source.CREATED_DATE = Now
                newCust_Income_Source.CREATED_BY = clsSessionMenuRight.getUserName
                KYCEntity.AddToMCUST_INCOME_SOURCE(newCust_Income_Source)
            Next
            KYCEntity.SaveChanges()
        Catch ex As Exception
            Throw ex
            'Catch ex As System.Data.SqlClient.SqlException
            '    Dim lvsERROR As String = ex.Message.ToString
            '    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" & lvsERROR & "')", True)
        End Try




    End Sub

#End Region

#Region "ผลิตภัณฑ์"

    Sub Bind_Data_togrid_Product()

        '''' Connect Data to Grid '''''''''''
        Me.dtProduct.Columns.Add("PRODUCTNAME")
        Me.dtProduct.Columns.Add("PRODUCTCODE")
        Me.dtProduct.Columns.Add("RISK")
        Me.dtProduct.Columns.Add("ACTIVE")

        Dim lvsCustType As Integer = Session("KYC")

        Dim QryProduct = (From tbName In KYCEntity.MCUST_PRODUCT
                        Where tbName.CUSTSEQ = CustSeq
                       Select tbName.SEQ,
                              tbName.PRODUCTNAME,
                              tbName.PRODUCTCODE,
                              tbName.RISK,
                              ACTIVE = If(tbName.ACTIVE = "Y", True, False)
                     Order By SEQ)

        For Each mRow In QryProduct
            Me.dtProduct.Rows.Add(mRow.PRODUCTNAME,
                                 mRow.PRODUCTCODE,
                                 mRow.RISK,
                                 mRow.ACTIVE)

            Me.dtProduct.AcceptChanges()
        Next

        Me.grdPRODUCT.DataSource = Me.dtProduct
        Me.grdPRODUCT.DataBind()
        ''''Number of Rows ''''''''''''''''''''''''''''''''''
        Me.lblCount_Product.Text = Me.dtProduct.Rows.Count
        '''''''''''''''''''''''''''''''''''''''''''''''''''''
        Session("PopProduct") = Me.dtProduct

    End Sub

    Protected Sub chk_ACT_PRODUCT_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        ''''check Session ''''''''''''''''''''''
        If Not (Session("PopProduct") Is Nothing) Then
            Me.dtProduct = Session("PopProduct")
        End If

        '''''' assign checkbox value to data table 
        For i = 0 To Me.grdPRODUCT.Rows.Count - 1
            Me.dtProduct.Rows(i).Item("ACTIVE") = CType(Me.grdPRODUCT.Rows(i).Cells(3).FindControl("chk_ACT_PRODUCT"), CheckBox).Checked
        Next i

        Me.dtProduct.AcceptChanges()
        Me.grdPRODUCT.DataSource = Me.dtProduct
        Me.grdPRODUCT.DataBind()

        Session("PopProduct") = Me.dtProduct
    End Sub

    Function Validate_Product() As Boolean
        Validate_Product = False

        ''''''''Validate ข้อมูลซ้ำ''''''''''''''''''
        Dim mProduct As String = ""
        For Each rowProduct As GridViewRow In grdPRODUCT.Rows
            mProduct = rowProduct.Cells(1).Text
            If mProduct = ddlPRODUCT_NAME.SelectedItem.Text Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ข้อมูลซ้ำ ! กรูณาเลือกผลิตภัณฑ์');", True)
                ddlPRODUCT_NAME.Focus()
                Exit Function
            End If

        Next
        '''''''''''''''''''''''''''''
        Validate_Product = True
    End Function

    Protected Sub btAddProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btAddProduct.Click
        Add_To_grid_Product()
    End Sub

    Sub Add_To_grid_Product()

        If Validate_Product() = False Then Exit Sub

        'check session of data table
        If Not (Session("PopProduct") Is Nothing) Then
            Me.dtProduct = Session("PopProduct")
        End If

        '''''''' insert data to grid row '''''''''''''''''''''''''''''''''''''''''''''''''

        '''''''''''''
        Dim dtRisk_Level As DataTable = New DataTable
        Dim lvsRisk As Integer = 1

        lvsSQL = ""
        lvsSQL += "     SELECT RISK                                                         "
        lvsSQL += "       FROM KYCADMIN.MPRODUCT                                            "
        lvsSQL += "      WHERE PRODUCTCODE = '" & Me.ddlPRODUCT_NAME.SelectedItem.Value & "'"

        dtRisk_Level = clsDatabase.QueryDataTable(lvsSQL)

        If (dtRisk_Level.Rows.Count <> 0) Then
            If Not IsDBNull(dtRisk_Level.Rows(0)("RISK")) Then lvsRisk = dtRisk_Level.Rows(0)("RISK")
        End If
        ''''''''''

        dtProduct.Rows.Add(Me.ddlPRODUCT_NAME.SelectedItem,
                          Me.ddlPRODUCT_NAME.SelectedValue,
                          lvsRisk,
                          True)
        dtProduct.AcceptChanges()
        Me.grdPRODUCT.DataSource = dtProduct
        Me.grdPRODUCT.DataBind()
        ''''Number of Rows ''''''''''''''''''''''''''''''''''
        Me.lblCount_Product.Text = Me.dtProduct.Rows.Count
        '''''''''''''''''''''''''''''''''''''''''''''''''''''
        ''''deselect ''''''''''''''''''''' 
        Me.grdPRODUCT.SelectedIndex = -1
        ''''''''''''''''''''''''''''''''''
        '''''now bind datatable to gridview... 
        Session("PopProduct") = Me.dtProduct

        ''''Clear Screen'''''''''

        Me.ddlPRODUCT_NAME.Focus()
    End Sub

    Protected Sub btDelProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btDelProduct.Click
        Me.Delete_gridRow_grdProduct()
    End Sub

    Sub Delete_gridRow_grdProduct()
        Try

            Dim index As Integer = grdPRODUCT.SelectedIndex
            If index = -1 Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "clientScript", "alert('ต้องเลือกผลิตภัณฑ์ที่ต้องการลบก่อน')", True)
            Else
                'check session of data table
                If Not (Session("PopProduct") Is Nothing) Then
                    Me.dtProduct = Session("PopProduct")
                End If
                ''''remove row at...
                dtProduct.Rows.RemoveAt(index)
                dtProduct.AcceptChanges()

                ''''bind data again
                grdPRODUCT.DataSource = Me.dtProduct
                grdPRODUCT.DataBind()
                ''''Number of Rows ''''''''''''''''''''''''''''''''''
                Me.lblCount_Product.Text = Me.dtProduct.Rows.Count
                '''''''''''''''''''''''''''''''''''''''''''''''''''''

                ''''deselect ''''''''''''''''
                grdPRODUCT.SelectedIndex = -1
                '''''''''''''''''''''''''''''
            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Page,
                                                Page.GetType(),
                                                "clientScript",
                                                "alert('" + ex.Message.Replace("'", "") + "')",
                                                True)
        End Try

    End Sub

    Protected Sub grdPRODUCT_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdPRODUCT.SelectedIndexChanged
        If grdPRODUCT.SelectedIndex = intBeforeSelectIndex_Product Then
            grdPRODUCT.SelectedIndex = -1
        End If
    End Sub

    Protected Sub grdPRODUCT_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdPRODUCT.SelectedIndexChanging
        Me.intBeforeSelectIndex_Product = grdPRODUCT.SelectedIndex
    End Sub

    Protected Sub Save_to_Cust_Product(ByVal key As Integer)

        Dim mProductName As String = ""
        Dim mProductCode As String = ""
        Dim mPrd_Risk As String = ""
        Dim chActive As String = ""
        Dim lvsCustType As Integer = Session("KYC")
        '''''''''''''''''''''''

        Try

            Dim DeletedQuery = (From m In KYCEntity.MCUST_PRODUCT
                               Where m.CUSTSEQ = key _
                              Select m).ToList

            If DeletedQuery.Count > 0 Then
                For i As Integer = 0 To DeletedQuery.Count - 1
                    KYCEntity.MCUST_PRODUCT.DeleteObject(DeletedQuery(i))
                Next i
            End If
            ''''''''''''''''''''''
            For Each rowID As GridViewRow In Me.grdPRODUCT.Rows
                Dim newCust_Product As New MCUST_PRODUCT

                ''''get values from Gridview '''''''
                mProductName = rowID.Cells(1).Text : If mProductName = "&nbsp;" Then mProductName = ""
                mProductCode = rowID.Cells(2).Text : If mProductCode = "&nbsp;" Then mProductCode = ""
                mPrd_Risk = rowID.Cells(3).Text : If mPrd_Risk = "&nbsp;" Then mPrd_Risk = ""

                If (CType(rowID.Cells(4).FindControl("chk_ACT_PRODUCT"), CheckBox).Checked = True) Then
                    chActive = "Y"
                Else
                    chActive = "N"
                End If


                ''''''''''''''''''''''''''''''''''''

                '''''''LINQ Start here ''''''''''''''
                newCust_Product.CUSTSEQ = key
                newCust_Product.CUSTTYPE = Session("KYC")
                newCust_Product.SEQ = rowID.RowIndex + 1
                newCust_Product.PRODUCTCODE = mProductCode
                newCust_Product.PRODUCTNAME = mProductName
                newCust_Product.RISK = mPRD_RISK
                newCust_Product.ACTIVE = chActive
                newCust_Product.CREATED_DATE = Now
                newCust_Product.CREATED_BY = clsSessionMenuRight.getUserName
                KYCEntity.AddToMCUST_PRODUCT(newCust_Product)
            Next
            KYCEntity.SaveChanges()
        Catch ex As Exception
            Throw ex
            'Catch ex As System.Data.SqlClient.SqlException
            '    Dim lvsERROR As String = ex.Message.ToString
            '    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" & lvsERROR & "')", True)
        End Try



    End Sub


#End Region

#Region "บริการเสริม"

    Sub Bind_Data_togrdAddedService()

        '''' Connect Data to Grid '''''''''''
        Me.dtAddedService.Columns.Add("ADDEDSERVICENAME")
        Me.dtAddedService.Columns.Add("ADDEDSERVICECODE")
        Me.dtAddedService.Columns.Add("RISK")
        Me.dtAddedService.Columns.Add("ACTIVE")

        Dim lvsCustType As Integer = Session("KYC")

        Dim qryAddedService = (From tbName In KYCEntity.MCUST_ADDED_SERVICE
                        Where tbName.CUSTSEQ = CustSeq
                       Select tbName.SEQ,
                              tbName.ADDEDSERVICENAME,
                              tbName.ADDEDSERVICECODE,
                              tbName.RISK,
                              ACTIVE = If(tbName.ACTIVE = "Y", True, False)
                     Order By SEQ)

        For Each mRow In qryAddedService
            Me.dtAddedService.Rows.Add(mRow.ADDEDSERVICENAME,
                                 mRow.ADDEDSERVICECODE,
                                 mRow.RISK,
                                 mRow.ACTIVE)

            Me.dtAddedService.AcceptChanges()
        Next

        Me.grdAddedService.DataSource = Me.dtAddedService
        Me.grdAddedService.DataBind()
        ''''Number of Rows ''''''''''''''''''''''''''''''''''
        Me.lblCount_AddedService.Text = Me.dtAddedService.Rows.Count
        '''''''''''''''''''''''''''''''''''''''''''''''''''''
        Session("PopAddedService") = Me.dtAddedService

    End Sub

    Protected Sub chk_ACT_ADDEDSERVICE_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        ''''check Session ''''''''''''''''''''''
        If Not (Session("PopAddedService") Is Nothing) Then
            Me.dtAddedService = Session("PopAddedService")
        End If

        '''''' assign checkbox value to data table 
        For i = 0 To Me.grdAddedService.Rows.Count - 1
            Me.dtAddedService.Rows(i).Item("ACTIVE") = CType(Me.grdAddedService.Rows(i).Cells(3).FindControl("chk_ACT_ADDEDSERVICE"), CheckBox).Checked
        Next i

        Me.dtAddedService.AcceptChanges()
        Me.grdAddedService.DataSource = Me.dtAddedService
        Me.grdAddedService.DataBind()

        Session("PopAddedService") = Me.dtAddedService
    End Sub

    Function Validate_AddedService() As Boolean
        Validate_AddedService = False

        ''''''''Validate ข้อมูลซ้ำ''''''''''''''''''
        Dim mProduct As String = ""
        For Each rowProduct As GridViewRow In grdAddedService.Rows
            mProduct = rowProduct.Cells(1).Text
            If mProduct = ddlADDED_SERVICE.SelectedItem.Text Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertMessage", "window.alert('ข้อมูลซ้ำ ! กรูณาเลือกบริการเสริมอื่น');", True)
                ddlADDED_SERVICE.Focus()
                Exit Function
            End If

        Next
        '''''''''''''''''''''''''''''
        Validate_AddedService = True
    End Function

    Protected Sub btAdd_ADDEDSERVICE_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btAdd_ADDEDSERVICE.Click
        Add_To_grdAddedService()
    End Sub

    Sub Add_To_grdAddedService()

        If Validate_AddedService() = False Then Exit Sub

        'check session of data table
        If Not (Session("PopAddedService") Is Nothing) Then
            Me.dtAddedService = Session("PopAddedService")
        End If

        '''''''' insert data to grid row '''''''''''''''''''''''''''''''''''''''''''''''''

        '''''''''''''
        Dim dtRisk_Level As DataTable = New DataTable
        Dim lvsRisk As Integer = 1

        lvsSQL = ""
        lvsSQL += "     SELECT RISK                                                             "
        lvsSQL += "       FROM KYCADMIN.MADDITION_SERVICE                                       "
        lvsSQL += "      WHERE ADSERVICECODE = '" & Me.ddlADDED_SERVICE.SelectedItem.Value & "'  "

        dtRisk_Level = clsDatabase.QueryDataTable(lvsSQL)

        If (dtRisk_Level.Rows.Count <> 0) Then
            If Not IsDBNull(dtRisk_Level.Rows(0)("RISK")) Then lvsRisk = dtRisk_Level.Rows(0)("RISK")
        End If
        ''''''''''
        dtAddedService.Rows.Add(Me.ddlADDED_SERVICE.SelectedItem,
                          Me.ddlADDED_SERVICE.SelectedValue,
                          lvsRisk,
                          True)
        dtAddedService.AcceptChanges()
        Me.grdAddedService.DataSource = dtAddedService
        Me.grdAddedService.DataBind()
        ''''Number of Rows ''''''''''''''''''''''''''''''''''
        Me.lblCount_AddedService.Text = Me.dtAddedService.Rows.Count
        '''''''''''''''''''''''''''''''''''''''''''''''''''''
        ''''deselect ''''''''''''''''''''' 
        Me.grdAddedService.SelectedIndex = -1
        ''''''''''''''''''''''''''''''''''
        '''''now bind datatable to gridview... 
        Session("PopAddedService") = Me.dtAddedService

        ''''Clear Screen'''''''''

        Me.ddlADDED_SERVICE.Focus()
    End Sub

    Protected Sub btDelAddedService_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btDelAddedService.Click
        Me.Delete_gridRow_grdAddedService()
    End Sub

    Sub Delete_gridRow_grdAddedService()
        Try

            Dim index As Integer = grdAddedService.SelectedIndex
            If index = -1 Then
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "clientScript", "alert('ต้องเลือกบริการเสริมที่ต้องการลบก่อน')", True)
            Else
                'check session of data table
                If Not (Session("PopAddedService") Is Nothing) Then
                    Me.dtAddedService = Session("PopAddedService")
                End If
                ''''remove row at...
                dtAddedService.Rows.RemoveAt(index)
                dtAddedService.AcceptChanges()

                ''''bind data again
                grdAddedService.DataSource = Me.dtAddedService
                grdAddedService.DataBind()
                ''''Number of Rows ''''''''''''''''''''''''''''''''''
                Me.lblCount_AddedService.Text = Me.dtAddedService.Rows.Count
                '''''''''''''''''''''''''''''''''''''''''''''''''''''

                ''''deselect ''''''''''''''''
                grdAddedService.SelectedIndex = -1
                '''''''''''''''''''''''''''''
            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Page,
                                                Page.GetType(),
                                                "clientScript",
                                                "alert('" + ex.Message.Replace("'", "") + "')",
                                                True)
        End Try

    End Sub

    Protected Sub grdAddedService_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdAddedService.SelectedIndexChanged
        If grdAddedService.SelectedIndex = intBeforeSelectIndex_AddedService Then
            grdAddedService.SelectedIndex = -1
        End If
    End Sub

    Protected Sub grdAddedService_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdAddedService.SelectedIndexChanging
        Me.intBeforeSelectIndex_AddedService = grdAddedService.SelectedIndex
    End Sub

    Protected Sub Save_to_Cust_AddedService(ByVal key As Integer)

        Dim mADDEDSERVICENAME As String = ""
        Dim mADDEDSERVICECODE As String = ""
        Dim mADDEDSERV_RISK As String = ""
        Dim chActive As String = ""
        Dim lvsCustType As Integer = Session("KYC")
        '''''''''''''''''''''''

        Try

            Dim DeletedQuery = (From m In KYCEntity.MCUST_ADDED_SERVICE
                               Where m.CUSTSEQ = key _
                              Select m).ToList

            If DeletedQuery.Count > 0 Then
                For i As Integer = 0 To DeletedQuery.Count - 1
                    KYCEntity.MCUST_ADDED_SERVICE.DeleteObject(DeletedQuery(i))
                Next i
            End If
            ''''''''''''''''''''''
            For Each rowAddedService As GridViewRow In Me.grdAddedService.Rows
                Dim newCust_AddedService As New MCUST_ADDED_SERVICE

                ''''get values from Gridview '''''''
                mADDEDSERVICENAME = rowAddedService.Cells(1).Text : If mADDEDSERVICENAME = "&nbsp;" Then mADDEDSERVICENAME = ""
                mADDEDSERVICECODE = rowAddedService.Cells(2).Text : If mADDEDSERVICECODE = "&nbsp;" Then mADDEDSERVICECODE = ""
                mADDEDSERV_RISK = rowAddedService.Cells(3).Text : If mADDEDSERV_RISK = "&nbsp;" Then mADDEDSERV_RISK = ""

                If (CType(rowAddedService.Cells(4).FindControl("chk_ACT_ADDEDSERVICE"), CheckBox).Checked = True) Then
                    chActive = "Y"
                Else
                    chActive = "N"
                End If


                ''''''''''''''''''''''''''''''''''''

                '''''''LINQ Start here ''''''''''''''
                newCust_AddedService.CUSTSEQ = key
                newCust_AddedService.CUSTTYPE = Session("KYC")
                newCust_AddedService.SEQ = rowAddedService.RowIndex + 1
                newCust_AddedService.ADDEDSERVICECODE = mADDEDSERVICECODE
                newCust_AddedService.ADDEDSERVICENAME = mADDEDSERVICENAME
                newCust_AddedService.RISK = mADDEDSERV_RISK
                newCust_AddedService.ACTIVE = chActive
                newCust_AddedService.CREATED_DATE = Now
                newCust_AddedService.CREATED_BY = clsSessionMenuRight.getUserName
                KYCEntity.AddToMCUST_ADDED_SERVICE(newCust_AddedService)
            Next
            KYCEntity.SaveChanges()
        Catch ex As Exception
            Throw ex
            'Catch ex As System.Data.SqlClient.SqlException
            '    Dim lvsERROR As String = ex.Message.ToString
            '    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" & lvsERROR & "')", True)
        End Try

    End Sub


#End Region

    Protected Sub btnAddConcern_Person_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddConcern_Person.Click
        Dim flag = 0
        CustSeq = Session("CUSTSEQ")

        If CustSeq = 0 Then
            If checkBefore_AddNonIndividualCorp() Then
                addNewCustomer(CustSeq)
                Session("TypeKYC") = 2
                flag = 1
            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" & strMsg & "')", True)
            End If
        Else
            flag = 1
        End If

        If flag = 1 Then
            Dim _script = String.Format("window.showModalDialog('NonIndividualCorp.aspx?index=-1&CustSeq={0}&CustType={1}&BIZCODE={2}&NAMETH={3}', ", _
                                        Session("CUSTSEQ"), Session("KYC").ToString(), txtBizNo.Text, txtNameTH.Text)
            _script = _script + "null, 'status:no; dialogWidth:1000px; dialogHeight:600px; help:no; scroll:yes; menubar:no; resizable:no'); "
            _script = _script + String.Format("document.getElementById('{0}').click();", btnUpdate_grdRef.ClientID)

            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "clientScript", _script, True)

        End If
    End Sub

    Function checkBefore_AddNonIndividualCorp() As Boolean
        Try
            Dim result As Boolean = True
            clsCheckLanguage = New clsCheckLanguage
            clsCheckID = New clsCheckID

            If txtBizNo.Text = "" Then
                result = False
                Image1.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotBizID + "\n"
            Else
                If Not txtBizNo.Text = hdfUniqueID.Value Then
                    If clsCheckID.checkUniqueID2(txtBizNo.Text, TypeKYC, CustSeq) = False Then
                        result = False
                        Image1.ImageUrl = "~/img/icon/cancel.png"
                        clsCheckID = Nothing
                        strMsg = strMsg + Resources.resMsgAlertKYC.UniqueBizNo + "\n"
                    Else
                        Image1.ImageUrl = "~/img/icon/accept.png"
                    End If
                Else
                    Image1.ImageUrl = "~/img/icon/accept.png"
                End If

            End If

            If ddlBizType.SelectedValue Is DBNull.Value Then
                result = False
                Image2.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotBizType + "\n"
            ElseIf ddlBizType.SelectedIndex = 0 Then
                result = False
                Image2.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotBizType + "\n"
            ElseIf ddlBizType.SelectedValue = 2 Then
                If Not (ddlBusiness1.SelectedValue > 51 And ddlBusiness1.SelectedValue < 60) And Not (ddlBusiness2.SelectedValue > 51 And ddlBusiness2.SelectedValue < 60) And Not (ddlBusiness3.SelectedValue > 51 And ddlBusiness3.SelectedValue < 60) Or Not ddlTranType.SelectedValue = 3 Then
                    If Not txtBizNo.Text.Trim.Length = 13 Then
                        result = False
                        Image1.ImageUrl = "~/img/icon/cancel.png"
                        strMsg = strMsg + Resources.resMsgAlertKYC.CheckBizNo + "\n"
                    Else
                        Image2.ImageUrl = "~/img/icon/accept.png"
                    End If
                Else
                    Image2.ImageUrl = "~/img/icon/accept.png"
                End If

            Else
                Image2.ImageUrl = "~/img/icon/accept.png"
            End If

            If txtNameTH.Text = "" Then
                result = False
                Image5.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + "กรุณากรอก ชื่อนิติบุคคล" + "\n"
            End If

            If ddlNationality.SelectedIndex = 0 Then
                result = False
                Image6.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotNationality + "\n"
            Else
                Image6.ImageUrl = "~/img/icon/accept.png"
            End If

            If ddlIncomeSource1.SelectedIndex = 0 Then
                result = False
                Image8.ImageUrl = "~/img/icon/cancel.png"
                strMsg = strMsg + Resources.resMsgAlertKYC.NotIncomeSource + "\n"
            Else
                Image8.ImageUrl = "~/img/icon/accept.png"
            End If

            statusValidation()
            clsCheckID = Nothing
            clsCheckLanguage = Nothing

            Return result
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Private Sub addNewCustomer(ByVal CustSeq As Integer)

        clsDatabase = New clsDatabase
        KYCEntity = New KYCEntities
        KYCEntity.Connection.Open()
        Using transaction As System.Data.Common.DbTransaction = KYCEntity.Connection.BeginTransaction()
            Try
                sql = "select " & System.Configuration.ConfigurationSettings.AppSettings("SequentMCUSTOMER_S") & " from dual"
                If (ds.Tables.Contains("GENCUST")) Then
                    ds.Tables("GENCUST").Clear()
                    ds.Tables("GENCUST").ImportRow(clsDatabase.QueryDataSet(sql, "GENCUST").Tables("GENCUST").Rows(0))
                Else
                    ds.Tables.Add(clsDatabase.QueryDataSet(sql, "GENCUST").Tables("GENCUST").Copy)
                End If
                CustSeq = ds.Tables("GENCUST").Rows(0)("NEXTVAL")
                Session("CUSTSEQ") = ds.Tables("GENCUST").Rows(0)("NEXTVAL")

                Dim clsMoney As New clsMoney
                Dim newCustomer As New MCUSTOMER

                newCustomer.TRANTYPE = ddlTranType.SelectedValue
                newCustomer.CUSTSEQ = CustSeq
                newCustomer.CUSTTYPE = 2
                newCustomer.CUSTSUBTYPE = ddlBizType.SelectedValue
                newCustomer.AMLCDDOVERVIEW = lblLevelCom.Text.Trim
                newCustomer.AMLREASONOVERVIEW = txtReason.Text.Trim

                newCustomer.UNIQUEID = txtBizNo.Text.Trim
                newCustomer.THFIRSTNAME = txtNameTH.Text.Trim
                newCustomer.ENFIRSTNAME = txtNameEN.Text.ToUpper.Trim
                newCustomer.NATIONALITY = ddlNationality.SelectedValue

                newCustomer.SALARYPERMONTH = 0
                newCustomer.ISANSWERSALARY = Convert.ToInt32(rdoAnsSalary.SelectedValue)

                If Not ddlBusiness1.SelectedIndex = 0 Then
                    newCustomer.BIZTYPE1 = ddlBusiness1.SelectedValue
                    newCustomer.BIZTYPEOTHER1 = txtBizOther1.Text.Trim
                Else
                    newCustomer.BIZTYPE1 = Nothing
                    newCustomer.BIZTYPEOTHER1 = ""
                End If

                newCustomer.BIZDESC1 = txtDes1.Text.Trim

                newCustomer.INCOMESOURCE1 = ddlIncomeSource1.SelectedValue

                newCustomer.AMLCDDBEFORE = lblOverview.Text.Trim
                newCustomer.AMLCDD = lblOverview.Text.Trim
                newCustomer.AMLREASON = txtReasonOverview.Text.Trim

                If Session("KYC") = 1 Then
                    newCustomer.DEPUPDATE = "D"
                    newCustomer.DEPD = "N"
                    newCustomer.DEPL = "-"
                    newCustomer.DEPP = "-"
                    newCustomer.DEPN = "-"
                ElseIf Session("KYC") = 2 Then
                    newCustomer.DEPUPDATE = "L"
                    newCustomer.DEPL = "N"
                    newCustomer.DEPD = "-"
                    newCustomer.DEPP = "-"
                    newCustomer.DEPN = "-"
                ElseIf Session("KYC") = 3 Then
                    newCustomer.DEPUPDATE = "P"
                    newCustomer.DEPP = "N"
                    newCustomer.DEPD = "-"
                    newCustomer.DEPL = "-"
                    newCustomer.DEPN = "-"
                ElseIf Session("KYC") = 5 Then
                    newCustomer.DEPUPDATE = "N"
                    newCustomer.DEPP = "-"
                    newCustomer.DEPD = "-"
                    newCustomer.DEPL = "-"
                    newCustomer.DEPN = "N"

                End If
                newCustomer.UPDATEBY = clsSessionMenuRight.getUserName

                newCustomer.BRANCHCODE = clsSessionMenuRight.getBranchCode
                newCustomer.ZONECODE = clsSessionMenuRight.getZoneCode
                newCustomer.DEPTCODE = clsSessionMenuRight.getDeptCode
                newCustomer.ALLCODERIGHT = clsSessionMenuRight.getAllCodeRight

                newCustomer.CREATEBY = clsSessionMenuRight.getUserName
                newCustomer.CREATEDATE = Now.ToShortDateString

                newCustomer.UPDATEDATE = Now.ToShortDateString
                If Not ddlTranType.SelectedValue = 2 Then
                    newCustomer.ETL_STATUS = "W"
                Else
                    newCustomer.ETL_STATUS = "N"
                End If

                KYCEntity.AddToMCUSTOMER(newCustomer)
                KYCEntity.SaveChanges()
                transaction.Commit()
            Catch ex As Exception
                transaction.Rollback()
                KYCEntity = Nothing
                Throw ex
            End Try
        End Using
    End Sub

     Protected Sub btnUpdate_grdRef_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate_grdRef.Click
        Dim dt_all = SearchData(Session("CUSTSEQ").ToString())

        'Dim dt1 = From group1 In dt_all _
        '          Order By group1("GROUP_CODE") And group1("GROUP_CODE_SUB") And group1("GROUP_CODE_SUB_SEQ") Ascending
        '          Select group1

        If dt_all.Rows.Count() > 0 Then
            ds.Tables("dsCustomerCom").Rows.Clear() ' clear DataTable dsCustomerCom

            For Each r In dt_all.Rows
                Dim drCust As DataRow = ds.Tables("dsCustomerCom").NewRow
                drCust("CustSEQ") = r("CUSTSEQ").ToString()
                drCust("CreateBy") = "AutoGenPK"
                drCust("CustType") = r("CUSTTYPE") ' 1 = บุคคลม 2 = นิติบุคคล
                drCust("CustSubType") = 1
                drCust("CUSTIDTYPE") = DBNull.Value
                drCust("AMLCDD") = r("RISK_LEVEL").ToString()
                drCust("AMLREASON") = ""
                drCust("UNIQUEID") = r("UNIQUEID")
                drCust("ThPreFix") = r("THPREFIX")
                drCust("ThFirstName") = r("INDV_FIRST_NAME")
                drCust("ThMidName") = ""
                drCust("ThLastName") = r("INDV_LAST_NAME")
                drCust("ENPreFix") = DBNull.Value
                drCust("EnFirstName") = ""
                drCust("EnMidName") = ""
                drCust("EnLastName") = ""

                drCust("POCODE") = r("GROUP_CODE").ToString + r("GROUP_CODE_SUB").ToString
                drCust("PONAME") = r("GROUP_CODE_SUB_NAME")
                ds.Tables("dsCustomerCom").Rows.Add(drCust)
            Next

            grdRef.DataSource = ds.Tables("dsCustomerCom")
        Else
            grdRef.DataSource = ds.Tables("dsCustomerCom") 'New DataTable()
        End If
        grdRef.DataBind()

    End Sub


    Private Function SearchData(ByVal CUSTSEQ As String, Optional ByVal CORP_LEVEL As Integer = -1, Optional ByVal CORP_SEQ As Integer = -1) As DataTable
        Dim dt As New DataTable
        Dim clsVariable As clsVariable
        Dim cltParameter As New Collection
        Dim dtAdapter As New OleDbDataAdapter

        Try
            Dim strSql As String = "select * from kycadmin.MCUST_CORP_CONC "
            strSql += "where CUSTSEQ = :CUSTSEQ and UNIQUEID IS NOT NULL "
            strSql += "order by GROUP_CODE, GROUP_CODE_SUB, GROUP_CODE_SUB_SEQ asc"

            clsVariable = New clsVariable
            clsVariable.nameColumn = "CUSTSEQ"
            clsVariable.valueColumn = CUSTSEQ
            cltParameter.Add(clsVariable)

            If CORP_LEVEL <> -1 Then
                strSql += "and CORP_LEVEL = :CORP_LEVEL "
                clsVariable = New clsVariable
                clsVariable.nameColumn = "CORP_LEVEL"
                clsVariable.valueColumn = CORP_LEVEL
                cltParameter.Add(clsVariable)
            End If

            If CORP_SEQ <> -1 Then
                strSql += "and CORP_SEQ = :CORP_SEQ"
                clsVariable = New clsVariable
                clsVariable.nameColumn = "CORP_SEQ"
                clsVariable.valueColumn = CORP_SEQ
                cltParameter.Add(clsVariable)
            End If

            Dim clsDB As New clsDatabase()
            dt = clsDB.QueryDataTableAddParameter(strSql, cltParameter)
            cltParameter.Clear()

        Catch ex As Exception
            Throw ex
        End Try

        Return dt

    End Function
#Region "Function"

    Public Function Gen_CusSeq(ByVal lvsRow_No As Integer) As Integer

        Try

            Dim dtCustSEQ As DataTable = New DataTable
            Dim lvsCustSeq As Integer

            dtCustSEQ = Nothing

            lvsSQL = ""
            lvsSQL += "     SELECT MAX (CUSTSEQ) + '" & lvsRow_No & "' AS CUSTSEQ   "
            lvsSQL += "       FROM KYCADMIN.MCUSTOMER                               "
            dtCustSEQ = clsDatabase.QueryDataTable(lvsSQL)

            If (dtCustSEQ.Rows.Count <> 0) Then
                lvsCustSeq = dtCustSEQ.Rows(0)("CUSTSEQ")
            End If

            Return lvsCustSeq

        Catch ex As Exception
            Console.WriteLine("")

        End Try

    End Function


#End Region

#Region "ประเมินความเสี่ยง"

    Protected Sub btnFind_Higthest_Score_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind_Higthest_Score.Click
        Me.FindHeighest_Score_All()
    End Sub

    Sub FindHeighest_Score_All()

        If Me.lblFILTER_RESULT_CUST.Text = "" Then
            btnFilter_CUST.Focus()
            Exit Sub
        End If

        If CInt(lblCount_Corp_Cate.Text) = 0 Then
            Me.ddlBusiness1.Focus()
            Exit Sub
        End If

        Me.lblEVAL_Sanct_list.Text = Me.lblFILTER_RESULT_CUST.Text
        Me.lblEVAL_Sanct_Score.Text = Me.lblRISK_LEVEL_CUST.Text
        Me.Find_Score_Corp_Conc()
        Me.Find_Score_BO()
        Me.Find_Score_Corp_Cate()
        Me.Find_Score_Nation()
        Me.Find_Score_Inc_Source()

        Me.Find_Score_Added_Service()
        Me.Find_Score_Added_Product()
        Me.Find_Score_Residence()
    End Sub

    Sub Find_Score_Corp_Conc()
        Try
            Dim dt As DataTable
            Dim err As String
            dt = GridviewToDataTable(grdRef, "3", err)

            Dim dataView As New DataView(dt)
            dataView.Sort = "3 Desc"  '3 Is Risk Score Column
            dt = dataView.ToTable()

            Dim RiskName As String = dt.Rows(0)("0").ToString()
            Dim RiskScore As String = dt.Rows(0)("3").ToString()

            Me.lblEVAL_Sanct_list_Corp_Conc.Text = Mid(RiskName, 1, 20)
            Me.lblEVAL_Sanct_Score_Corp_Conc.Text = RiskScore

        Catch ex As Exception

        End Try
    End Sub
    Sub Find_Score_BO()
        Try
            Dim dt As DataTable
            Dim err As String
            dt = GridviewToDataTable(grdBo, "19", err)

            Dim dataView As New DataView(dt)
            dataView.Sort = "19 Desc"  '3 Is Risk Score Column
            dt = dataView.ToTable()

            Dim RiskName As String = dt.Rows(0)("2").ToString()
            Dim RiskScore As String = dt.Rows(0)("19").ToString()

            Me.lblEVAL_Sanct_list_BO.Text = Mid(RiskName, 1, 20)
            Me.lblEVAL_Sanct_Score_BO.Text = RiskScore

        Catch ex As Exception

        End Try
    End Sub

    Sub Find_Score_Residence()

        Dim dtRisk_Level As DataTable = New DataTable

        lvsSQL = ""
        lvsSQL += "     SELECT NATIONALITYNAME,             "
        lvsSQL += "            RISK                         "
        lvsSQL += "       FROM KYCADMIN.MNATIONALITY        "
        lvsSQL += "      WHERE NATIONCODE = '202'           "
        dtRisk_Level = clsDatabase.QueryDataTable(lvsSQL)

        If (dtRisk_Level.Rows.Count <> 0) Then
            If Not IsDBNull(dtRisk_Level.Rows(0)("NATIONALITYNAME")) Then Me.lblEVAL_RESIDENT.Text = dtRisk_Level.Rows(0)("NATIONALITYNAME")
            If Not IsDBNull(dtRisk_Level.Rows(0)("RISK")) Then Me.lblEVAL_RESIDENT_SCORE.Text = dtRisk_Level.Rows(0)("RISK")
        End If
    End Sub
    Sub Find_Score_Added_Product()
        Try
            Dim dt As DataTable
            Dim err As String
            dt = GridviewToDataTable(Me.grdPRODUCT, "3", err)

            Dim dataView As New DataView(dt)
            dataView.Sort = "3 Desc"  '3 Is Risk Score Column
            dt = dataView.ToTable()

            Dim RiskName As String = dt.Rows(0)("1").ToString()
            Dim RiskScore As String = dt.Rows(0)("3").ToString()

            Me.lblEVAL_PRODUCT.Text = Mid(RiskName, 1, 20)
            Me.lblEVAL_PRODUCT_SCORE.Text = RiskScore

        Catch ex As Exception

        End Try
    End Sub

    Sub Find_Score_Added_Service()
        Try
            Dim dt As DataTable
            Dim err As String
            dt = GridviewToDataTable(Me.grdAddedService, "3", err)

            Dim dataView As New DataView(dt)
            dataView.Sort = "3 Desc"  '3 Is Risk Score Column
            dt = dataView.ToTable()

            Dim RiskName As String = dt.Rows(0)("1").ToString()
            Dim RiskScore As String = dt.Rows(0)("3").ToString()


            Me.lblEVAL_ADD_SERV.Text = Mid(RiskName, 1, 20)
            Me.lblEVAL_ADD_SERV_SCORE.Text = RiskScore

        Catch ex As Exception

        End Try
    End Sub

    Sub Find_Score_Corp_Cate()
        Try
            Dim dt As DataTable
            Dim err As String
            dt = GridviewToDataTable(Me.grdCorp_Cate, "5", err)

            Dim dataView As New DataView(dt)
            dataView.Sort = "5 Desc"  '3 Is Risk Score Column
            dt = dataView.ToTable()

            Dim RiskName As String = dt.Rows(0)("1").ToString()
            Dim RiskScore As String = dt.Rows(0)("5").ToString()


            Me.lblEVAL_OCC.Text = Mid(RiskName, 1, 20)
            Me.lblEVAL_OCC_SCORE.Text = RiskScore

        Catch ex As Exception

        End Try
    End Sub

    Sub Find_Score_Inc_Source()
        Try
            Dim dt As DataTable
            Dim err As String
            dt = GridviewToDataTable(grdIncome, "4", err)

            Dim dataView As New DataView(dt)
            dataView.Sort = "4 Desc"  ' Is Risk Score Column
            dt = dataView.ToTable()

            Dim RiskName As String = dt.Rows(0)("1").ToString()
            Dim RiskScore As String = dt.Rows(0)("4").ToString()

            Me.lblEVAL_INC_SOURCE.Text = Mid(RiskName, 1, 20)
            Me.lblEVAL_INC_SOURCE_SCORE.Text = RiskScore

        Catch ex As Exception

        End Try
    End Sub

    Sub Find_Score_Nation()
        Try
            Me.lblEVAL_NATION.Text = Mid(ddlNationality.SelectedItem.Text, 1, 20)
            Me.lblEVAL_NATION_SCORE.Text = Me.lblRISK_LEVEL_NATION.Text

        Catch ex As Exception

        End Try
    End Sub

    Public Shared Function GridviewToDataTable(ByVal PassedGridView As GridView, ByVal lvscol As String, ByRef Error_Message As String) As DataTable
        '-----------------------------------------------
        'Dim Tbl_StackSheets = New Data.DataTable
        'Tbl_StackSheets = ReportsCommonClass.GridviewToDataTable(StackSheetsGridView)

        '-----------------------------------------------

        Dim dt As New DataTable
        Dim ColInd As Integer = 0
        Dim ValOffset As Integer
        Dim ColCount As Integer = 0

        Try

            For Each col As DataControlField In PassedGridView.Columns
                If lvscol = ColCount Then
                    dt.Columns.Add(ColCount.ToString(), GetType(Int32))
                Else
                    dt.Columns.Add(ColCount.ToString())
                End If
                ColCount += 1
            Next

            If (PassedGridView.AutoGenerateDeleteButton Or PassedGridView.AutoGenerateEditButton Or PassedGridView.AutoGenerateSelectButton) Then
                ValOffset = 1
            Else
                ValOffset = 0
            End If

            For Each row As GridViewRow In PassedGridView.Rows
                Dim NewDataRow As DataRow = dt.NewRow

                ColInd = 0
                For Each col As DataControlField In PassedGridView.Columns
                    NewDataRow(ColInd) = row.Cells(ColInd + ValOffset).Text.Replace("&nbsp;", "")
                    ColInd += 1
                Next

                dt.Rows.Add(NewDataRow)
            Next

            Error_Message = Nothing

        Catch ex As Exception
            Error_Message = "GridviewToDataTable: " & ex.Message
        End Try


        Return dt


    End Function

#End Region

    Protected Sub ddlPrefixTH_BO_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlPrefixTH_BO.SelectedIndexChanged
        Me.ddlPrefixEN_BO.SelectedValue = Me.ddlPrefixTH_BO.SelectedValue
    End Sub

    Protected Sub ddlPrefixEN_BO_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlPrefixEN_BO.SelectedIndexChanged
        Me.ddlPrefixTH_BO.SelectedValue = Me.ddlPrefixEN_BO.SelectedValue
    End Sub

#Region "Set ReadOnly"
    Private Sub SetControl_Enable()
        Dim kyc = Request.QueryString("KYC")
        If kyc = 1 Then
            Me.txtCIF_FDR_NO.ReadOnly = True : Me.txtCIF_FDR_NO.BackColor = Drawing.Color.Silver
            Me.txtCIF_NPA_NO.ReadOnly = True : Me.txtCIF_NPA_NO.BackColor = Drawing.Color.Silver
        Else
            Me.txtCIF_FDR_NO.ReadOnly = False : Me.txtCIF_FDR_NO.BackColor = Drawing.Color.White
            Me.txtCIF_NPA_NO.ReadOnly = False : Me.txtCIF_NPA_NO.BackColor = Drawing.Color.White
        End If
    End Sub
#End Region

    Sub Find_next_Review()
        Try

            Dim dtSmartCard As DataTable = New DataTable
            Dim lvsNextMonth As DataTable = New DataTable

            Me.lblPERIOD_MONTH.Text = 0

            lvsSQL = ""
            lvsSQL += "     SELECT PERIOD_MONTH                                 "
            lvsSQL += "       FROM KYCADMIN.MRISK_LEVEL                         "
            lvsSQL += "      WHERE RISK_LEVEL = '" & Me.lblLevelCom.Text & "'   "
            dtSmartCard = clsDatabase.QueryDataTable(lvsSQL)

            If (dtSmartCard.Rows.Count <> 0) Then
                If Not IsDBNull(dtSmartCard.Rows(0)("PERIOD_MONTH")) Then Me.lblPERIOD_MONTH.Text = dtSmartCard.Rows(0)("PERIOD_MONTH")
            End If


            lvsSQL = ""
            lvsSQL += "    SELECT TO_CHAR (ADD_MONTHS(TO_DATE (SYSDATE), '" & CInt(Me.lblPERIOD_MONTH.Text) & "'), 'DD/MM/YYYY') AS NEXT_REVIEW "
            lvsSQL += "       FROM DUAL                                                                     "
            lvsNextMonth = clsDatabase.QueryDataTable(lvsSQL)

            If (lvsNextMonth.Rows.Count <> 0) Then
                If Not IsDBNull(lvsNextMonth.Rows(0)("NEXT_REVIEW")) Then Me.lblNEXT_REVIEW.Text = lvsNextMonth.Rows(0)("NEXT_REVIEW")
                If Len(Me.lblNEXT_REVIEW.Text) = 10 Then
                    Me.lblNEXT_REVIEW.Text = Mid((Me.lblNEXT_REVIEW.Text), 1, 6) & CInt(Mid((Me.lblNEXT_REVIEW.Text), 7, 4)) + 543
                End If

            End If



        Catch ex As Exception
            '  Console.WriteLine("")
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                                    "clientScript",
                                    "alert('" + ex.Message.Replace("'", "") + "')",
                                    True)

        End Try
    End Sub
End Class


